SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
Note
This chapter is written using Python 2.6 syntax; it will be converted to Python 3 at a later date.
Objects are created by other objects: special objects called “classes” that we can set up to spit out objects that are configured to our liking.
Classes are just objects, and they can be modified the same way:
>>> class Foo: pass ... >>> Foo.field = 42 >>> x = Foo() >>> x.field 42 >>> Foo.field2 = 99 >>> x.field2 99 >>> Foo.method = lambda self: "Hi!" >>> x.method() 'Hi!'
To modify a class, you perform operations on it like any other object. You can add and subtract fields and methods, for example. The difference is that any change you make to a class affects all the objects of that class, even the ones that have already been instantiated.
What creates these special “class” objects? Other special objects, called metaclasses.
The default metaclass is called type and in the vast majority of cases it does the right thing. In some situations, however, you can gain leverage by modifying the way that classes are produced – typically by performing extra actions or injecting code. When this is the case, you can use metaclass programming to modify the way that some of your class objects are created.
It’s worth re-emphasizing that in the vast majority of cases, you don’t need metaclasses, because it’s a fascinating toy and the temptation to use it everywhere can be overwhelming. Some of the examples in this chapter will show both metaclass and non-metaclass solutions to a problem, so you can see that there’s usually another (often simpler) approach.
Some of the functionality that was previously only available with metaclasses is now available in a simpler form using class decorators. It is still useful, however, to understand metaclasses, and certain results can still be achieved only through metaclass programming.