Day33.定制元类控制类的产生
1.定制元类控制类的产生_类People继承类Mymeta
'''如何自定义元类(type)来控制类的产生''' # todo metaclass=type:代表继承原有的元类type # class People(metaclass=type): # todo metaclass=Mymeta:代表继承自定义的元类Mymeta class Mymeta(type): # 只有继承了type类的类才是元类 # 4个传参:空对象, 'People', (object,), {...} def __init__(self, x, y, z): print('run....') print(self) print(x) print(y) print(z) # People = Mymeta(class_name, class_bases, class_dic) # People = Mymeta('People', (object,), {...}) # 调用Mymeta发生的三件事 # 1. 先造一个空对象 ==> People # 2. 调用Mymeta这个类内的__init__方法,完成初始化对象的操作 # 3. 返回初始化好的对象 class People(object, metaclass=Mymeta): def __init__(self, name, age): self.name = name self.age = age def say(self): print('{}:{}'.format(self.name, self.age))
2.定制元类控制类的产生_判断People类名开头是否是大写字母
'''如何自定义元类(type)来控制类的产生''' # todo metaclass=type:代表继承原有的元类type # class People(metaclass=type): # todo metaclass=Mymeta:代表继承自定义的元类Mymeta class Mymeta(type): # 只有继承了type类的类才是元类 # 4个传参:空对象, 'People', (object,), {...} def __init__(self, x, y, z): # todo .istitle()判断调用的类名开头是否是大写字母 if not x.istitle(): # todo 类程序抛出异常 raise NameError('类名字的首字母必须大写') # People = Mymeta(class_name, class_bases, class_dic) # People = Mymeta('People', (object,), {...}) # 调用Mymeta发生的三件事 # 1. 先造一个空对象 ==> People # 2. 调用Mymeta这个类内的__init__方法,完成初始化对象的操作 # 3. 返回初始化好的对象 # class People(object, metaclass=Mymeta): class people(object, metaclass=Mymeta): def __init__(self, name, age): self.name = name self.age = age def say(self): print('{}:{}'.format(self.name, self.age))