-
自定义一个元类,控制类的产生,类的名称空间中必须有name字段才能创建成功,否则失败
class Mymeta(type):
def __init__(self, class_name, class_bases, class_dic):
if 'name' not in class_dic:
raise TypeError('类名必须加"name"')
super(Mymeta, self).__init__(class_name, class_bases, class_dic)
class People(metaclass=Mymeta):
# name = 'nick'
def __init__(self, age):
self.age = age
lbm = People(19)
print(lbm.age)
-
自定义一个元类,定义一个类,继承字典,使其具备点取值和赋值功能,通过元类控制对象的产生,把所有对象的属性都放到attr字典中,属性全删除
例如:Mydict(name = 'lqz', age = 18)
实例化对象的名称空间没有name和age属性,但是有attr:字典属性,字典内包含{'name':'lqz', 'age':18}'
duixinag.__dict__' {attr:{'name':'lqz', 'age':18},}
class myclass(type):
def __call__(self, *args, **kwargs): #空对象
obj = self.__new__(self) #定制
obj['attr'] = kwargs
#obj['attr'] = {i:v for i,v in kwargs.items()}
return obj
class son(dict,metaclass=myclass):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def __getattr__(self,item):
return self[item]
def __setattr__(self, key, value):
self[key] = value
obj = son(name = 'tom',age = 20,)
print(obj)
https://www.cnblogs.com/abdm-989/p/11453773.html