Object-Oriented Senior B

Moto类

python everything is an object, an object class is actually a

Class is an object, he must be obtained from a class instance of this class is called metaclass

How to find metaclass

class Person:
    def __init__(self, name):
        self.name = name
    def score(self):
        print('分数是100')

print(type(Person))

#<class 'type'>

#所有类的元类都是type 

Conventional class class class name constructed will actually generate meta class instances of this object class,

** the Person object class, the class must be instantiated by one generation, so the type () to generate the object, call the __init__ method, which need to see the source code through three parameters **

The principle underlying class is: type (object_or_name, bases, dict),

  1. object_or_name: name of the class, is a string

  2. bases: all its parent class, the base class

  3. dict: namespace is a dictionary

#通过type来直接产生类,不用class关键字
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,), l) # 等同于生成一个Person类,其中具有school属性,对象有name属性,有score方法


### 下面几句可以生成一个Person类,与上面的语句实现相同的功能
#def __init__(self, name):
    #self.name = name
#Person = type('Person', (object,), {'school':'
# oldboy','__init__':__init__})


Custom metaclass

Produces to control class, you can control the class name, you can control the class hierarchy, control namespace class

Custom metadata class must inherit type, write a class that inherits type, this class called metaclass

class Mymeta(type):
    def __init__(self, name, bases,dic):
        #练习一:加限制 控制类名必须以sb 开头
        if not name.startswith('sb'):
            raise Exception(’类名没有以sb开头‘)# 如果不是以sb开头,就会抛异常
        #练习二:类必须加注释
        print(self.__dict__['__doc__']) # 有注释的话会把注释打印出来
#metaclass=Mymeta 指定这个类生成的时候,用自己写的Mymeta这个元类

class Person(object,metaclass=Mymeta):
    '''
    注释
    '''
    school = 'oldboy'
    def __init__(self, name):
        self.name = name
    def score(self):
        print('分数是100')
        
p = Person('nick')
  1. A custom metaclass, class control production, the class name space must have a name field in order to create successful, otherwise fail
class Mymeta(type):
    def __init__(self, x, y, z):
        for k, v in self.__dict__.items():
            print(k,v)
        # print(self.__dict__)
        if 'name' not in self.__dict__.values() and 'name'not in self.__dict__.keys():
            raise Exception('你的类没有“name”这个字段')
        else:
            print('名称空间已经存在"name"')
  1. Custom yuan a class, define a class that inherits the dictionary, it has a point value and assignment features, objects produced by metaclass control, the properties of all objects are placed attr dictionary, delete all properties

E.gdi=Mydict(name='lqz', age=18) di的名称空间中没有name和age属性,但是有attr字典属性,字典包含{'name':'lqz', 'age':18}

class Mymeta(type):
    def __init__(self, *args, **kwargs):
        self.attr = {}

class Mydict(dict, metaclass=Mymeta):
    attr = {}
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
    def __getattr__(self, item):
        # print(item)
        return self[item]
    def __setattr__(self, key, value):
        if value not in self.attr:
            self.attr[key] = value
            print(self.attr)

Guess you like

Origin www.cnblogs.com/michealjy/p/11456351.html