Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
What is a metaclass in python? (stackoverflow.com)
79 points by o1iver on Aug 8, 2011 | hide | past | favorite | 8 comments


Here are two other great answer by this guy (one is on the HN front page right now):

Yield: http://stackoverflow.com/questions/231767/the-python-yield-k...

Decorators: http://stackoverflow.com/questions/739654/understanding-pyth...


this is sure one hell of an explanation. here's a shorter one from me:

simply put, you need metaclasses when you want to overload the "instantiation operator". the __new__ in a metaclass is used for making changes to a class before instantiation, and __init__ is used for making changes after instantiation. the implicit first argument to __init__ and other instance methods in a metaclass (conventionally called self) is the implicit first argument to class methods in the metaclass instance (conventionally called cls)

note that "metaclass instance" and "class definition" are synonyms.

i can't think of a use case where __call__ would be useful, because it's technically the ctor of the metaclass instance. also, i think that using callables other than 'type' subclasses is being too clever with an already complicated concept, so i'd avoid doing it.

this is based on my practical experience with metaclasses, so i might have missed something. but that's all i'm using metaclasses for anyway.


I really like this trend of in-depth Stack-Overflow explanations... especially about Python because it helps me a lot. Keep up the good work.


I agree with you. Do you know of any non-python answers?

Edit: why the downvote??


Not sure why someone would downvote that... but yes, there are also lots of Javascript answers that seem to follow the same trend.


The best metaclass explanation I have read is "Metaclasses Demystified" (http://cleverdevil.org/computing/78/), which originally appeared in Python Magazine.



Is English not the author's native language, or was this written hastily? This answer is littered with awkward grammatical errors.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: