Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PyConZA 2013: "Python meta-classes" by Kisitu A...

Pycon ZA
October 04, 2013

PyConZA 2013: "Python meta-classes" by Kisitu Augustine

An attempt to demystify meta classes and show what they are, what they do and when you might need them.

This talk is for anyone who would like to see what happens under the hood when you create a class in Python and how to intercept the class creation process and modify it.

Pycon ZA

October 04, 2013
Tweet

More Decks by Pycon ZA

Other Decks in Programming

Transcript

  1. Python  Meta  Classes   Kisitu  Augus)ne   So.ware  Developer  at

     ThoughtWorks   Twi:er:  @aus)ine04   Github:  aus)ine04  
  2. Classes  create  instances.         Class  Foo(object):  

             def  _  _init_  _(self,  bar):                  self.bar  =  bar             f  =  Foo(‘Alex  Bar’)  
  3. Class  Foo(object):          def  _  _init_  _(self,

     bar):                    self.bar  =  bar       At  run)me  class  Foo  is  an  instance  of  type  
  4. De5ining  a  meta  class   class  Meta(type):      

         def  _  _init_  _(cls,  name,  bases,  dict):                  pass            def  _  _new_  _(meta,  name,  bases,  dct):                    pass                      def  _  _call_  _(cls,  *args,  **kwargs):                    pass  
  5. class  Foo(object):          _  _metaclass_  _  =

     Meta                    def  _  _init_  _(self):                  pass    
  6. class  Foo(metaclass  =  Meta):            def

     _  _init_  _(self):                  pass    
  7. def  log(func)on):          def  wrapper_func)on(*args,  **kwargs):  

                   print  “Calling  ……….”,  func)on.__name__                  return  func)on(*args,  **kwargs)          return  wrapper_func)on  
  8. Things  can  get  quite  ugly  if  you  are  inheri)ng  from

      mul)ple  classes  each  with  its  own  meta  class.