标签:__name__ war attr %s 作用 ldb get title code
作用:控制类的调用过程,实际上在控制:对象的产生
控制名称空间
class Mymeta(type):
def __call__(self,*args, **kwargs):
obj=self.__new__(self)#生成空对象
obj.__init__(*args, **kwargs)#调用obj的__init__()
obj.__dict__['attr']=kwargs
return obj
class Mydict(dict,metaclass=Mymeta):
def __getattr__(self, item):
return self.__dict__['attr'][item]
def __setattr__(self, key, value):
self[key]=value
self.__dict__['attr'][key] = value
----------------------------------------------------
di=Mydict(name='nick',age=18)
print(di.__dict__)
print(di.name)
di.sex='male'
print(di)
print(di.__dict__)
-----------------------------------------------------
{'attr': {'name': 'nick', 'age': 18}}
nick
{'name': 'nick', 'age': 18, 'sex': 'male'}
{'attr': {'name': 'nick', 'age': 18, 'sex': 'male'}}
例2练习:给我吧对象中的所有属性都设置成私有的
class Mymeta(type):
def __call__(self, *args, **kwargs):
obj=object.__new__(self)
obj.__init__(*args, **kwargs)
# print(obj.__dict__)
obj.__dict__={ '_%s__%s'%(self.__name__,k):v for k,v in obj.__dict__.items()}
# print(obj.__dict__)
return obj
class Person(object, metaclass=Mymeta):
school = 'oldboy'
def __init__(self, name):
self.name = name
def score(self):
print('分数是100')
p = Person(name='nick')
print(p.__dict__) #{'_Person__name': 'nick'}
print(p.name) #会报错
标签:__name__ war attr %s 作用 ldb get title code
原文地址:https://www.cnblogs.com/demiao/p/11456347.html