Python Metaclasses

Download Python Metaclasses

Post on 25-Jun-2015

379 views

Category:

Technology

2 download

Embed Size (px)

DESCRIPTION

A talk i did at PyConZA 2013

TRANSCRIPT

<ul><li> 1. Python Meta Classes Kisitu Augustine Software Developer at ThoughtWorks Twitter: @austiine04 Github: austiine04 </li></ul> <p> 2. SOME BASICS 3. Everything is an object in python. 4. Classes create instances. Class Foo(object): def _ _init_ _(self, bar): self.bar = bar f = Foo(Alex Bar) 5. type(f) 6. Creating new types 7. Class Foo(object): pass 8. Class Foo: pass 9. Foo = type(Foo, (), {}) 10. type(cls,*args,**kwargs) 11. type() is actually not a function. It is a META CLASS. 12. A special kind of class that creates classes. 13. type(name, bases, cls_dct) 14. Class Foo(object): def _ _init_ _(self, bar): self.bar = bar At runtime class Foo is an instance of type 15. Defining 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 16. _ _new_ _() vs _ _init_ _() 17. class Foo(object): _ _metaclass_ _ = Meta def _ _init_ _(self): pass 18. class Foo(metaclass = Meta): def _ _init_ _(self): pass 19. Show us the code 20. Example #1 Making a class final 21. Example #2 Decorating class methods 22. def log(function): def wrapper_function(*args, **kwargs): print Calling ., function.__name__ return function(*args, **kwargs) return wrapper_function 23. Some advanced basics 24. A class is an instance of its metaclass at runtime. 25. Metaclasses go down the inheritance chain. 26. Things can get quite ugly if you are inheriting from multiple classes each with its own meta class. 27. With great power comes great responsibility 28. Questions ??? </p>

Recommended

View more >