5 ms·
What is a metaclass in python?
- o1iver 15y agoHere 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-keyword-explained/231855#231855 http://stackoverflow.com/questions/231767/the-python-yield-k... Decorators: http://stackoverflow.com/questions/739654/understanding-python-decorators/1594484#1594484 http://stackoverflow.com/questions/739654/understanding-pyth...
- barnaby 15y agoI really like this trend of in-depth Stack-Overflow explanations... especially about Python because it helps me a lot. Keep up the good work.
- baddox 15y agoIs English not the author's native language, or was this written hastily? This answer is littered with awkward grammatical errors.
- plq 15y agothis 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.
- fuzzythinker 15y agoI really like this one also: http://www.ibm.com/developerworks/linux/library/l-pymeta2 http://www.ibm.com/developerworks/linux/library/l-pymeta2
- espeed 15y agoThe best metaclass explanation I have read is "Metaclasses Demystified" (http://cleverdevil.org/computing/78/ http://cleverdevil.org/computing/78/), which originally appeared in Python Magazine.