练习一:在元类中控制把自定义类的数据属性都变成大写
1 class MyMeta(type): 2 def __new__(cls, class_name, class_bases, class_dic): 3 update_attrs = {} 4 for i in class_dic: 5 if not callable(class_dic[i]) and not i.startswith('__'): 6 update_attrs[i.upper()] = class_dic[i] 7 else: 8 update_attrs[i] = class_dic[i] 9 return type.__new__(cls, class_name, class_bases, update_attrs) 10 11 12 class Chinese(metaclass=MyMeta): 13 country = 'China' 14 tag = 'Legend of the Dragon' 15 16 def __init__(self, name): 17 self.name = name 18 19 def talk(self): 20 print('%s is talking' % self.name) 21 22 23 ch = Chinese('alice') 24 print(Chinese.__dict__) 25 ''' 26 {'__module__': '__main__', 'COUNTRY': 'China', 'TAG': 'Legend of the Dragon', 27 '__init__': <function Chinese.__init__ at 0x00000235649C0B70>, 28 'talk': <function Chinese.talk at 0x00000235649C0BF8>, 29 '__dict__': <attribute '__dict__' of 'Chinese' objects>, 30 '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None} 31 32 '''
练习二:在元类中控制自定义的类无需init方法
1.元类帮其完成创建对象,以及初始化操作;
2.要求实例化时传参必须为关键字形式,否则抛出异常TypeError: must use keyword argument
3.key作为用户自定义类产生对象的属性,且所有属性变成大写
1 class Mymeta(type): 2 def __call__(self, *args, **kwargs): 3 if args: 4 raise TypeError('must use keyword argument') 5 obj = object.__new__(self) 6 for i in kwargs: 7 obj.__dict__[i.upper()] = kwargs[i] 8 return obj 9 10 11 class Chinese(metaclass=Mymeta): 12 country = 'China' 13 tag = 'Lengend of the Dragon' 14 def talk(self): 15 print('%s is talking' % self.NAME) 16 17 18 ch = Chinese(name='alice', age=12) 19 print(ch.__dict__) 20 ch.talk() 21 ''' 22 {'NAME': 'alice', 'AGE': 12} 23 alice is talking 24 '''