python--Five-minute understanding meta-class (Metaclasses)

Source: Internet
Author: User

"The Magic of meta-class is more than 99% of users worry, when you do not understand whether you really need to use it, is not necessary." ”

-tim Peters

This article stems from a quick speech on Pycon UK 2008.

The meta-class is called "Esoteric Witchcraft" in Python. Although you need to use it very rarely (unless you're programming based on Zope), the fact that its basic theory is actually surprisingly understandable.

All objects

    • All objects
    • Everything has a type
    • There is essentially no difference between "class" and "type"
    • Class is also an object
    • Their types are type

Previously, the term type was used for built-in types, while the term class was used for user-defined classes, but "class" and "type" were not inherently different since Pythoon 2.2.

The type for the old style (Old-style) class is types. ClassType.

Really, it's true.

Python 2.5.1 (r251:54869, APR 18 2007, 22:08:04)
>>> class Something (object):
... Pass
...
>>> Something
<class ' __main__. Something ' >
>>> type (Something)
<type ' type ' >

From here you can see that the class created in the interactive interpreter is a first class object.

The class of the class is ...

Its meta-class ...

Just as an object is an instance of a class, a class is an instance of its meta class.

Call a meta-class to create a class.

in a precise sense, Python the same is true for other objects in the

So when you create a class ...

The interpreter calls the meta-class to generate it ...

Defining a normal class that inherits from object means calling the type to create it:

>>> Help (Type)

Help on class type in module __builtin__:

class type (object)

| Type (object), the object ' s type

| Type (name, bases, Dict), a new type

The second use of type is particularly important. When the Python interpreter executes a class definition statement, such as the first two lines of code in the example, it invokes the type with the following arguments:

    • Class name in string form
    • The base class sequence of tuples--in our case, is a tuple of only one element (' ONE-PL ') [1], such as (object).
    • A dictionary that includes class members (class properties, methods, and so on) that are mapped by names

Simple simulation

>>> def __init__ (self):
... self.message = ' Hello world '
...
>>> def Say_hello (self):
... Print Self.message
...
>>> attrs = {' __init__ ': __init__, ' Say_hello ': Say_hello}
>>> bases = (object,)
>>> Hello = type (' Hello ', bases, Attrs)
>>> Hello
<class ' __main__. Hello ' >
>>> h = Hello ()
>>> H.say_hello ()
Hello World

The above code creates a dictionary of class properties and then calls the type to create a class named Hello.

__metaclass__ The Magic

You can provide a custom meta-class whenever you set __metaclass__ in the class definition to any callable object with the same parameters as type.

You typically use a method that inherits from type:

class Pointlessmetaclass (type):
def __new__ (meta, name, bases, Attrs):
# do stuff ...
return type.__new__ (meta, name, bases, Attrs)

It is important that in the __new__ method we are able to read or change the arguments passed in to create a new class. This enables you to introspect property dictionaries and modify, add, or delete members.

Although both functions are called when instantiating a class, overwriting __new__ is more important than __init__. __init__ Initializes an instance, and __new__ 's responsibility is to create it. Therefore, if the meta-class is used to customize the creation of a class, you need to overwrite the __new__ of type.

The reason for using a new class instead of just providing a factory function is that the meta-class is not inherited if the factory function is used (that is, just calling type).

In Action ...

>>> class Whizzbang (object):
... __metaclass__ = Pointlessmetaclass
...
>>> Whizzbang
<class ' __main__. Whizzbang ' >
>>> type (Whizzbang)
<class ' __main__. Pointlessmetaclass ' >

Whizzbang is a class, but it is now not an instance of type, but an instance of our custom meta class ...

What's the use of this?

Good question, the meta-class will be invoked when creating a new class that uses it, here are some ideas about the benefits of doing so:

    • All methods of decorating (decorate) classes for logging or performance splitting.
    • New method of Automatic mix-in
    • Registers the class at creation time. (such as automatically registering plug-ins or creating database schemas from class members.) )
    • Provides interface registration, feature auto-discovery and interface adaptation.
    • Class check: Prevents subclasses and verifies that all methods have docstrings.

The most important thing is that the class is actually created when the last call to type is made, so you can freely change the dictionary of attributes (as well as the base class sequence in the form of names and tuples) as you like.

Some popular Python ORM (Object Relational mappers), which works with the database, also uses the meta-class.

Oh, and because the meta-class is inherited, you can provide a base class that uses your meta-class, and subclasses that inherit from it don't have to explicitly declare it.

But......

I didn't need to use it to write code ... (We use it to split, and it's widely used in ironclad projects, but I don't write these).

Also, this applies only to Python 2.x, where the mechanism has changed in Python 3.

Type (type) is type

In Python 2.6, it is now possible to use class decorators to implement many things that might have previously been required to be implemented in a meta class.

Finally, there is a very artifice example (slightly deeper, but still not difficult to digest), you can go to see the selfless metaclass. It avoids explicitly declaring self with bytecode and method signature overrides.

[1]

' ONE-PL ' refers to tuples with only one element.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.