‘‘‘不会3、在元类中控制自定义的类产生的对象相关的属性全部为隐藏属性4、基于元类实现单例模式‘‘‘‘‘‘1、在元类中控制把自定义类的数据属性都变成大写class Father(type): def __new__(cls,name,bases,dic): update_dic={} for k,v in dic.items(): update_dic.update({k.upper():v}) return type.__new__(cls,name,bases,update_dic) class Son(metaclass=Father): country=‘China‘ tag=‘Legend of the Dragon‘ def walk(self): print(‘唐老鸭 is walking‘) print(Son.__dict__)‘‘‘‘‘‘2、在元类中控制自定义的类无需__init__方法class Father(type): def __call__(self, *args, **kwargs): if args: raise TypeError(‘must use keyword argument for key function‘) obj = object.__new__(self) for k,v in kwargs.items(): obj.__dict__[k.upper()]=v return obj class Son(metaclass=Father): country=‘China‘ tag=‘Legend of the Dragon‘ #龙的传人 def walk(self): print(‘唐老鸭 is walking‘) p=Son(name=‘tank‘,age=18,sex=‘male‘)print(p.__dict__)‘‘‘
原文地址:https://www.cnblogs.com/0B0S/p/12706755.html
时间: 2024-11-09 18:55:24