0

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.

Aminah Nuraini
  • 18,120
  • 8
  • 90
  • 108
  • 3
    "metaclass and inheritance from superclass in Python serve a very similar purpose" - what? No. Where did you get that idea? Metaclasses serve a very different role. – user2357112 Sep 10 '16 at 07:31
  • At the very least it looks very similar for me as someone who just learn metaclass. May I know the differences? – Aminah Nuraini Sep 10 '16 at 07:33

1 Answers1

3

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?

Community
  • 1
  • 1
Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
  • Why would I want to customize the creation process? – Aminah Nuraini Sep 10 '16 at 07:42
  • 2
    "Metaclasses ... allow you to customise the process of creation of a class" - they let you customize much more than just the creation process. [You want a class `Color` where `Color['red']` works and does something meaningful?](https://docs.python.org/3/library/enum.html) Metaclasses let you do that. [You want a class `Iterable` where `isinstance(thing, Iterable)` is true if and only if `thing` is iterable?](https://docs.python.org/3/library/collections.abc.html) Metaclasses let you do that. – user2357112 Sep 10 '16 at 07:46
  • Perhaps to make sure that you return only one of a pre created set of classes (e.g. like a thread pool) or maybe (like in an ORM), you create a class with a bunch of attributes for db columns (e.g. date, name etc.) and you automatically get methods like "filter_by_date", "filter_by_name" etc. – Noufal Ibrahim Sep 10 '16 at 07:46