Classes as Objects
First, before you know metaclass, you need to know the class in Python. The strange nature of class in Python draws on the Smalltalk language. In most languages, classes is just the code end that describes how to create an object. In some ways, so is the class in Python.
>>> class Objectcreator (object):
... Pass
...
.. >>> my_object = Objectcreator ()
>>> print My_object
<__main__. Objectcreator Object at 0x8974f2c>
However, the classes in Python is also objects, yes, look right, objects, once you use the keyword Class,python will execute and generate an object, command
>>> class Objectcreator (object):
... Pass
An object with the name Objectcreator will be created in memory.
this object (class) has its own ability to create objects (instances), which is why it is called a class .
Because it is an object, it should have some attributes of the object: You can assign it to a variable you can copy it you can add properties to it you can take it as a function parameter
For example:
>>> Print Objectcreator # can print a class because it ' s an object
<class ' __main__. Objectcreator ' >
>>> def Echo (o): ... Print o
...
>>> Echo (objectcreator) # You can pass a class as a parameter
<class ' __main__. Objectcreator ' >
>>> print hasattr (objectcreator, ' New_attribute ')
False
>>> Objectcreator.new_attribute = ' foo ' # you can add attributes to a class
>>> print hasattr (objectcreator, ' NE W_attribute ')
True
>>> print objectcreator.new_attribute
foo
>>> Objectcreatormirror = objectcreator # can assign a class to a variable
>>> print objectcreatormirror.new _attribute
foo
>>> print objectcreatormirror ()
<__main__. Objectcreator Object at 0x8997b4c>
creating classes dynamically because classes are objects, you can create them like objects dynamically.
First, you can create it using keywords in a function:
>>> def choose_class (name):
... If name = = ' Foo ': ... Class Foo (object):
... Pass
... .. Return Foo # Return to the class, not a instance ... else: ... Class Bar (object):
... Pass
... .. Return Bar ...
>>> MyClass = choose_class (' foo ')
>>> print MyClass # The function returns a class, not a instance
<class ' __main__. Foo ' >
>>> print MyClass () # You can create a object from this class
<__main__. Foo Object at 0x89c6d4c>
However, this is not very dynamic because you still have to write the whole function yourself. Because classes are objects, they can be generated. When you use the keyword class, Python automatically creates these objects, so like most things in Python, we can also generate them manually.
Remember the function type. Is the function that tells you the object type:
>>> print type (1)
<type ' int ' >
>>> Print Type ("1")
<type ' str ' >
> >> print Type (objectcreator)
<type ' type ' >
>>> Print Type (Objectcreator ())
< Class ' __main__. Objectcreator ' >
Surprisingly, type also has a completely different ability, which is the dynamic creation function we need. Type can take the description of a class as an argument and then generate a class. The type works like this:
Type (name of the class,
tuple of the parent class (for inheritance, can is empty),
dictionary containing attribute s names and values)
For example:
>>> class Myshinyclass (object):
... Pass
You can create this manually by using the following methods:
>>> Myshinyclass = Type (' Myshinyclass ', (), {}) # Returns a Class object
>>> print Myshinyclass
<class ' __main__. Myshinyclass ' >
>>> print Myshinyclass () # Create a instance with the class
<__main__. Myshinyclass Object at 0x8997cec>
We can see that we use Myshinyclass as class name, the function is very obvious, just a few different parameter changes, there is no reason to complicate, in the words of the original author: They can be different,but there are no reason to Complicate things.
What are metaclasses (finally) finally to open is to explain metaclasses, I have been waiting for a long time, metaclasses are the ' stuff ' that creates classes. This is the author of the article said that it is a can create the class, you define the class is to create objects. But in Python we see classes as objects, and so,metaclasses is to create objects. They are class classes, and you can imagine them like this:
MyClass = Metaclass ()
MyObject = MyClass ()
You can see that type lets you do the same thing:
MyClass = Type (' MyClass ', (), {})
This is because the function type is actually a metaclass, in Python, type is a metaclass used to create a class in the background. Now you know why it uses lowercase, not uppercase type.
Well, did you think of Str/int and other functions, which Str used to create a string object, int to create an integer object, that type is just a class that creates a class object. You can see it by looking at the __class__ property. Everything is an object, so objects can be created by a function:
>>> age =
>>> age.__class__
<type ' int ' >
>>> name = ' Bob '
>> > name.__class__
<type ' str ' >
>>> def foo (): Pass
>>> foo.__class__
< Type ' function ' >
>>> Class Bar (object): Pass
>>> B = Bar ()
>>> B.__class_ _
<class ' __main__. Bar ' >
Who is the creator of the class created?
>>> age.__class__.__class__
<type ' type ' >
>>> name.__class__.__class__
< Type ' type ' >
>>> foo.__class__.__class__
<type ' type ' >
>>> b.__class__.__ class__
<type ' type ' >
This should be a little more clear, of course, we can also create our own metaclass.
The __metaclass__ attribute You can add a __metaclass__ property when creating a class:
Class Foo (object):
__metaclass__ = something ...
[...]
Python will use Metaclass to create Class Foo, be careful Oh, you write class Foo (object), but Foo is not yet created in memory, Python will look for it in your class __metaclass__ if found, use it to create, if not found , it uses type to create the class.
To be more specific, when you define a class:
Class Foo (object): Pass
Python will first see if there are any __metaclass__ attributes in the class definition, not looking in parent, not going to the module level, and if not, the final kill type.
Well, the final question is, what should we put in the __metaclass__?
Custom metaclasses The main purpose of a metaclass is to change it automatically when the class is created, and to read a little bit. Generally speaking, when you write some APIs, and these APIs to meet the current context, you can consider using Metaclass. Imagine that when the classes in your module need to write their properties as lowercase, we can try to metaclass at the moudle level, when all the classes in the module will be created by Metaclass, All we have to do is tell Metaclass to convert all the attributes to lowercase. Fortunately, we do not necessarily have to define __metaclass__ as a class:
# The Metaclass would automatically get passed the same argument # this you usually pass to ' type ' def upper_attr (future_cl
Ass_name, Future_class_parents, future_class_attr): "" "Return a class object, and the list of its attributes turned
into uppercase. "" "# Pick up any attribute that doesn ' t start with ' ___ ' and uppercase it uppercase_attr = {} for name, Val in Futu
Re_class_attr.items (): If not name.startswith (' __ '): Uppercase_attr[name.upper ()] = Val else: Uppercase_attr[name] = val # let ' type ' does the class creation return type (Future_class_name, future_class_parents , uppercase_attr) __metaclass__ = upper_attr # This'll affect all classes in the Module Class Foo (): # Global __metacl Ass__ won ' t work with "object" though # but we can define __metaclass__ here instead to affect only this class # and T His'll work with "object" children bar = ' Bip ' Print hasattr (foo, ' Bar ') # Out:false print hasattr (foo, ' Bar ') # out: True f = Foo () print F.bar # out: ' Bip ' Now, we use a class to implement Metaclass:
# Remember that ' type ' are actually a class like ' str ' and ' int ', ' can inherit from it class Upperattrmetaclass (type ): # __new__ is the method called before __init__ # It's the method of that creates the object and returns it # While __init__ just initializes the "object passed as parameter # you rarely use __new__, except if you are want to contr
Ol how the object # is created. # Here's the created object ' class, and we want to customize it # so we override __new__ # you can do some Stu
FF in __init__ too if your wish # Some advanced use involves overriding __call__ as down, but we won ' t #
def __new__ (Upperattr_metaclass, Future_class_name, Future_class_parents, future_class_attr):
Uppercase_attr = {} for name, Val in Future_class_attr.items (): If not name.startswith (' __ '):
Uppercase_attr[name.upper ()] = val Else:uppercase_attr[name] = val return type (Future_class_name, future_class_parents, uppercase_attr) But this is not a real oop. We can call the __new__ of type directly:
Class Upperattrmetaclass (Type):
def __new__ (Upperattr_metaclass, Future_class_name,
future_class_parents, FUTURE_CLASS_ATTR):
uppercase_attr = {}
for name, Val in Future_class_attr.items ():
if not name.startswith (' __ '):
uppercase_attr[name.upper ()] = val
else:
uppercase_attr[name] = val
# reuse the type.__new__ Method
# It is basic OOP, nothing magic in there return
type.__new__ (Upperattr_metaclass, future_class_name,< C11/>future_class_parents, Uppercase_attr)
You may have noticed the extra parameter upperattr_metaclass, which is nothing special: A method often takes the current instance as the first argument, like the self in the usual method. Of course, I see the long name here as a clearer explanation, like self, all parameters have a customary name, so it's a product Metaclass:
Class Upperattrmetaclass (Type):
def __new__ (CLS, clsname, Bases, DCT):
uppercase_attr = {}
for name, Val in D Ct.items ():
If not name.startswith (' __ '):
uppercase_attr[name.upper ()] = val
else:
uppercase_attr[ Name] = val return
type.__new__ (CLS, clsname, bases, uppercase_attr)
We can use super to make the code cleaner:
Class Upperattrmetaclass (Type):
def __new__ (CLS, clsname, Bases, DCT):
uppercase_attr = {}
for name, Val in Dct.items ():
If not name.startswith (' __ '):
uppercase_attr[name.upper ()] = val
else:
uppercase_ Attr[name] = val return
super (Upperattrmetaclass, CLS). __new__ (CLS, clsname, bases, uppercase_attr)
So much, Metaclass is so simple. In fact, the reason to use Metaclass code is not because of the use of metaclass, but because you often use metaclass to do some need introspection, operation inheritance/variables such as __dict__. In fact, Metaclass can do complex things, too. However, the following are not complicated:
Understand the creation of a class change class return a modified class
Why would you to use metaclasses classes instead of functions? Just keep on writing. Because __metaclass__ can accept arbitrary calls, why choose a class that looks more complex? For a few reasons:
The purpose of the construction of the class is quite clear, refer to the Upperattrmetaclass above (type) you can use OOP. Metaclass can inherit from Metaclass, overwriting the parent-class method you can better organize your code structure. Make code easy to read you can use __new__, __init__, __call__ will do metaclass, always have to do something. (This is rather far-fetched (:-)
Why the hell would use metaclasses? The Python guru writes an explanation that is too shallow to understand and does not translate, but he said an example is the ORM model used in Django, for example, we can define the data model as follows:
Class person (models. Model):
name = models. Charfield (max_length=30) Age
= models. Integerfield ()
But when you call this:
Guy = person (name= ' Bob ', age= ')
print Guy.age
It does not return the Integerfield object. It returns an int, and it can take a value from the database.
One explanation is models. Model defines the __metaclass__ and converts the simple person you define into a complex link to a database field.
Django uses a simple API to expose many complex things to make us look simple, and to regenerate code using APIs in the background via Metaclass.
The last word Finally, the author mentions the exception of type, and class alterations: meaning that most of the time we don't use class alteration, can be implemented using monkey patching and class decorators, so the space left to Metaclass is very small.
All the end ...
Detailed inventory of the article to see: Http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python
It's a pretty good one, too: http://xiaocong.github.io/blog/2012/06/12/python-metaclass/.
Occasionally look at StackOverflow python posts, benefited, today to see Metaclass speak too good, try to translate out to try, welcome everyone to communicate with each other.