metaclass in python

Home Forums Python Programming metaclass in python

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2138 Reply
    Humble
    Keymaster

    Whenever you create a class in python you would have noticed its of type “type”.

    >>> class A(object):
    ...     def __init__(self):
    ...             print "I am a constrcutor"
    ... 
    >>> type(A)
    <type 'type'>
    >>> A
    <class '__main__.A'>
    >>> 
    
    
    
    In simple terms, class A is created from "type" or in other way "type" is a metaclass of class A.
    
    As like we create objects from class , class is an object of "type".
    
    In other way, an object is an instance of its class; like that, a class is an instance of its metaclass or we would say class of a class is its metaclass.
    
    
    In one of the earlier posts ( ) I mentioned how to create a class using "type".. 
    
    
    instead of using "type" as your metaclass, you can use your own custom metaclass. If you remember, when we discussed @abstractmethod decorator we used abc.ABCMeta as our metaclass. It was achived by 
    
    __metaclass__ = ABCMeta
    
    in the class definition. 
    
    When we define our own metaclass, we inherit it from builtin "type" and manipulate __new__ method ( where the arguments are first passed from new class creation) of custom metaclass. Then return to builtin "type"'s __new__ method with the essential arguments.
Viewing 1 post (of 1 total)
Reply To: metaclass in python
Your information: