Search code examples
pythonclassinheritancesuperclassmetaclass

Why would I prefer metaclass over inheritance from a superclass in Python


From what I've learned so far, metaclass and inheritance from superclass in Python serve a very similar purpose, but superclass inheritance is more powerful.

Why would I prefer metaclass over superclass inheritance? In what kind of case metaclass would be helpful?

Sorry if there is any wrong assumption. I just learned metaclass today.


Solution

  • I think you've misunderstood. Inheritance is the classic object oriented technique of reusing code by putting the commonly used stuff in a base class and deriving from that.

    Metaclasses in a nutshell) allow you to customise the process of creation of a class (specifically the __new__ method) so that you can dynamically add attributes and things like that. It's a little complicated and in most cases, you won't need this. There are some details over at this answer What is a metaclass in Python?