# 4、在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性
class Mymeta4(type):
def __call__(self, *args, **kwargs):
obj = self.__new__(self)
self.__init__(obj, *args, **kwargs)
print('修改前:', obj.__dict__)
# 隐藏属性的命名: _类名__属性名
start_str = '_' + self.__name__ + '__'
print(start_str)
update_dic = {}
for k, v in obj.__dict__.items():
if not k.startswith(start_str):
update_key = start_str + k
update_dic[update_key] = v
else:
update_dic[k] = v
obj.__dict__ = update_dic
print('修改后:', obj.__dict__)
return obj
class Test(metaclass=Mymeta4):
def __init__(self, name, age):
self.name = name
self.age = age
obj = Test('test', 18)
print(obj.__dict__)
# 输出内容:
# 修改前: {'name': 'test', 'age': 18}
# _Test__
# 修改后: {'_Test__name': 'test', '_Test__age': 18}
# {'_Test__name': 'test', '_Test__age': 18}