Chapter XIII, metaclass (metaclass)

Chapter XIII, metaclass (metaclass)

First, what is the metaclass

  • Everything in python object, we use the class keyword to define the class itself is an object, the object's class is responsible for generating called metaclass that may be referred to as meta-class class class

    class Foo:  # Foo=元类()
        pass

    114-to ???? ç ± »meta class ç ±» ç ???? ???? to to "º.png? X-us-process = style / watermark

Second, why use metaclasses

  • Yuan class is responsible for generating the class, so we have to learn or a custom metaclass metaclass purpose: to control the production process and the like, you can also control the production process objects

  • Nature:

  • exec()

    l={}
    exec('''
    school='oldboy'
    def __init__(self,name):
        self.name=name
    def score(self):
        print('分数是100')
    ''',{},l)
    def __init__(self,name):
        self.name=name
    
    Person=type('Person',(object,),{'school':'oldboy','__init__':__init__})
    #class 底层就是调用type来实例化产生类(对象)
  • Difference supplementary #exec () eval () in

  • f = "3+6+9+8"
    s = eval(f)
    print(s)
    --------------------------
    26
  • code = '''
    def func():
        print('test')
        return 555
    func()
    '''
    
    f = exec(code)
    print('---'*5)
    print(f)
    -------------------------------
    test
    ---------------
    None

Guess you like

Origin www.cnblogs.com/demiao/p/11456236.html