Python Advanced Programming Meta-class (End of 3rd part)

Source: Internet
Author: User

#-*-Coding:utf-8-*-

# python:2.x

__author__ = ' Administrator '

#元编程

#new-style class provides the ability to modify the definition of classes and objects at run time through 2 special methods (__NEW__ and __metaclass__)

#__new__方法

#它是一上元构建程序, it is called every time an object is instantiated by the factor class

#例如:

Class A (object):

Def __new__ (CLS,):

print ' __new__ '

Return object.__new__ (CLS) #默认情况

def __init__ (self):

print ' __init__ '

Self.a=1

A=a ()

"""

__new__

__init__

-------------

The __new__ method must return an instance of a class, so it can modify the class before or after the object is created, which is helpful to ensure that the object constructor is not set to an unwanted state, or to add a program that cannot be deleted by the constructor.

For example, __init__ is not implicitly called in subclasses, so __new__ can be used to determine that initialization has been done in the entire class hierarchy, as follows

"""

Class AaI (A):p

Aaa=aai ()

"""

__new__

__init__

"""

Class MM (A):

def __init__ (self):

print ' MM class init '

Super (Mm,self). __init__ ()

self.b=2

CCC=MM ()

"""

__new__

MM class Init

__init__

"""

#例如, a network socket or database should be controlled in __new__ rather than __init__, because it notifies us when the class work must complete this initialization and must be inherited, for example

From threading Import Thread

Class Op (Thread):

def __init__ (self):

Pass

#print Op () assertionerror:thread.__init__ () is not called

"" This is actually done through assertions on the method (Assert self.__initialized), and can be simplified to a single call in __new__, because this instance has nothing else

"Avoid headaches with link initialization"

__NEW__ is the return required for implicit initialization of an object's state, which makes it possible to

An initialization is defined at a low level, and this initialization problem is called.

"""

#__metaclass__方法

The ability of the #元类提供了在关对象通过其工厂方法 (factory) to interact within the context of creation is similar to __new__, except that it runs at the class level, and the built-in type is the built-in base factory that generates the specified name, base class, and any mappings containing its attributes, as follows:

Def methio ():

Return

# klass=type (' MyClass ', (object), {' Methion ': Methio})

# Is1=klass ()

# Is1.methio ()

#与类显式定义类似

Class C (object):

def Me (self):

Return 12

Ss=c ()

Print ss.me () #12

"""

With this feature, you can create an interaction with the class before or after calling the type, and a special feature has been created to link to a custom factory

__metaclass__ (in python3000, which will be overridden by an explicit constructor parameter) can be added to a class definition to interact with the creation process. Its attributes must be set to:

1 Accept and type the same parameters (a class name, a set of base classes, an attribute map)

2 Returning a Class object

The completion of the above event is similar to the use of the non-binding function (equip function), there is another class object on a method, as long as 1 and 2 is sufficient, if the class has an empty docstring, then the descriptor is automatically added to the class, such as the following

"""

def eqiup (classname,tyoes,dicts):

If ' __dict__ ' not in dicts:

dicts[' __doc__ ']=api ()

return type (classname,tyoes,dicts)

Class Myclass (object):

__metalcass__=eqiup

def Alright (self):

"The OK Method"

Return ' OK '

Ma=myclass ()

Ma.__class__

ma.__class__.__dict__[' __doc__ ']

Ma.y=1

Print ma.__doc__

"""

This change may not work elsewhere, because __doc__ is the built-in primitive class type read-only attribute, but the meta-class makes the code more complex, and when it is used in classes of all classes of work, robustness becomes worse

For modifying a read-write feature or adding a new feature, you can avoid using meta-classes and use simpler methods based on dynamically modifying class instances, which are easier to manage because they do not need to be grouped into a class (the class can have only one meta-class)

For example

"""

Def a (Klass):

C=[l for L in klass.__name__ if L.isupper ()]

Klass.contracted_name= '. Join (c)

def b (Klass):

def logger (func):

def W (*a,**k):

print ' logger '

return func (*a,**k)

Return W

For E in Dir (Klass):

If E.startswith ('_'):

Continue

Value=getattr (Klass,e)

If not hasattr (value, ' Im_func '):

Continue

SetAttr (Klass,e,logger (value))

Def en (klass,*e):

For E21 in E:

E21 (Klass)

Class Ms (object):

def OK (self):

"I rweturn OK"

Return ' Lied '

En (MS,A,B)

T=ms ()

T.ok ()

#这是很强大的表现: You can dynamically create many different changes on a class definition that has already been instantiated

#在任何情况下, remember that a meta-class or dynamic increase is just a patch that may quickly make a well-defined, clear class hierarchy become a mess, using the following conditions

"""

At the frame level, when a behavior is mandatory in many classes

When a particular behavior is added to the purpose of not interacting with a class that provides functionality such as logging

--------------

For more examples, you can look at David Mertz a good introduction to meta-class programming, with the following URLs:

Www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html?page=1

"""

Python Advanced Programming Meta-class (End of 3rd part)

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.