Python (2 only?) looks at the value of variable __metaclass__
to determine how to create a type
object from a class definition. It is possible to define __metaclass__
at the module or package level, in which case it applies to all subsequent class definitions in that module.
However, I encountered the following in the flufl.enum
package's __init__.py
:
__metaclass__ = type
Since the default metaclass if __metaclass__
is not defined is type
, wouldn't this have no effect? (This assignment would revert to the default if __metaclass__
were assigned to at a higher scope, but I see no such assignment.) What is its purpose?
In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses.
A metaclass is a class that creates other classes. By default, Python uses the type metaclass to create other classes. For example, the following defines a Person class: class Person: def __init__(self, name, age): self.name = name self.age = age. Code language: Python (python)
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
In object-oriented computer programming, a metaclass is one whose instances are also classes. For instance, in Python, the built-in class type is a metaclass: instances of class type are themselves a class of objects. The use of metaclasses is most prevalent in object-oriented languages.
In Python 2, a declaration __metaclass__ = type
makes declarations that would otherwise create old-style classes create new-style classes instead. Only old-style classes use a module level __metaclass__
declaration. New-style classes inherit their metaclass from their base class (e.g. object
), unless __metaclass__
is provided as a class variable.
The declaration is not actually used in the code you linked to above (there are no class declarations in the __init__.py
file), but it could be. I suspect it was included as part of some boilerplate that makes Python 2 code work more like Python 3 (where all classes are always new-style).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With