Your SlideShare is downloading. ×

Advanced Python : Metaclasses

678

Published on

This presentation gives quick introduction to metaclasses in python. Download the file to view to the animation effects.

This presentation gives quick introduction to metaclasses in python. Download the file to view to the animation effects.

Published in: Technology, Education
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
678
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
5
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. MetaclassesBhanwar Singh
  • 2. Classes are Objects too !!!• We perceive class as a snippet of code whichproduces an object.• But in python a class is an object too. Anobject capable of producing other objects.• You can assign it to a variable• You can copy it• You can add attributes to it.• You can pass it as a function parameter.
  • 3. Metaclass• Metaclasses are the stuff that creates classes.• The function type is a metaclass. It is used bypython behind-the-scenes to create all classes.• You can call it a class factory if you wish.• Class of an object can be checked using__class__ attribute.• Metaclasses allow us to intercept andaugment class creation.
  • 4. How ‘type’ creates a class• At the end of a class statement, and after running all its nested code in anamespace dictionary, python calls the type object to create the classobject.class = type(classname, superclasses, attributedict)• The type object in turn defines a __call__ operator overloadingmethod that runs two other methods when the type object is called:type.__new__(typeclass, classname, superclasses, attributedict)type.__init__(class, classname, superclasses, attributedict)• The __new__ method creates and returns the new class object.• Then the __init__ method initializes the newly created object.
  • 5. The __metaclass__ attribute• It is used in class definition to specify themetaclass of the class.• When we create a class python will look forthe __metaclass__ attribute in classdefinition.• If found, that metaclass will be used for thecreation of the class.• If not found, then this hierarchy is used –parent class -> module -> type
  • 6. • We can specify our own metaclass!!!• Luckily, __metaclass__ can be any callable.It need not be class always.• The main purpose of a metaclass is to changethe class automatically, when its created.• You usually do this for APIs, where you wantto create classes matching the currentcontext.
  • 7. Coding Metaclasses• Metaclass can be any callable.• Hence we can create metaclass using afunction.• Or using a class• Next slides present few examples.
  • 8. Metaclass using a function#This function is the metaclass#This simply adds a class attribute to the class being created.def meta_Person(class_name, parent_class, attr_dict):print "Creating Person"attr_dict[is_human]=Truereturn type(class_name,parent_class,attr_dict)#This is the class which uses metaclassclass Person:def __init__(self,name,age):self.name=nameself.age=age__metaclass__ = meta_Personram = Person(Ram,23)shyam = Person(Shyam,25)print Person.is_humanprint ram.is_humanCreating PersonTrueTrueclass_name = name of the classparent_class = tuple of all parentclassesattr_dict = dictionary containing allclass attributes.
  • 9. Metaclass as subclass of ‘type’class MyMeta(type):def __new__(meta, name, bases, dct):print -----------------------------------print "Allocating memory for class", nameprint metaprint basesprint dctreturn super(MyMeta, meta).__new__(meta, name, bases, dct)def __init__(cls, name, bases, dct):print -----------------------------------print "Initializing class", nameprint clsprint basesprint dctsuper(MyMeta, cls).__init__(name, bases, dct)class MyKlass(object):__metaclass__ = MyMetadef foo(self, param):passbarattr = 2
  • 10. The output of previous program will be ------------------------------------Allocating memory for class MyKlass<class __main__.MyMeta>(<type object>,){barattr: 2, __module__: __main__, foo: <functionfoo at 0x01D8B130>, __metaclass__: <class__main__.MyMeta>}-----------------------------------Initializing class MyKlass<class __main__.MyKlass>(<type object>,){barattr: 2, __module__: __main__, foo: <functionfoo at 0x01D8B130>, __metaclass__: <class__main__.MyMeta>}It’s important to note here that these print-outs are actually done at class creationtime, i.e. when the module containing the class is being imported for the first time.Keep this detail in mind.
  • 11. Using __call__ function__call__ is called when already created class is instantiated to create a new object.class MyMeta(type):def __call__(cls, *args, **kwds):print __call__ of , str(cls)print __call__ *args=, str(args)return type.__call__(cls, *args, **kwds)class MyKlass(object):__metaclass__ = MyMetadef __init__(self, a, b):print MyKlass object with a=%s, b=%s % (a, b)print gonna create foo now...foo = MyKlass(1, 2)Outputgonna create foo now...__call__ of <class __main__.MyKlass>__call__ *args= (1, 2)MyKlass object with a=1, b=2
  • 12. Sources -http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037O’Reilly – Learning Python

×