Python----面向对象---练习一:在元类中控制把自定义类的数据属性都变成大写

在元类中控制把自定义类的数据属性都变成大写

 1 class Mymeta(type):
 2     def __new__(cls, class_name, class_bases, class_dic):
 3         print(cls)
 4         print(class_name)
 5         print(class_bases)
 6         print(class_dic)
 7         update_attrs = {}
 8         for k, v in class_dic.items():
 9             if not callable(v) and not k.startswith('__'):
10                 update_attrs[k.upper()] = v
11             else:
12                 update_attrs[k] = v
13         print(update_attrs)
14         return type.__new__(cls, class_name, class_bases, update_attrs)
15 
16 
17 class Chinese(object, metaclass=Mymeta):
18     '''
19     xxx
20     '''
21 
22     country = 'China'
23     tag = '123'
24 
25     def __init__(self, name, age):
26         self.name = name
27         self.age = age
28 
29     def talk(self):
30         print('%s is talking' % self.name)
31 
32 print(Chinese.__dict__)
33 
34 结果为:
35 
36 <class '__main__.Mymeta'>
37 Chinese
38 (<class 'object'>,)
39 {'__module__': '__main__', '__qualname__': 'Chinese', '__doc__': '\n    xxx\n    ', 'country': 'China', 'tag': '123', '__init__': <function Chinese.__init__ at 0x00000236B593B620>, 'talk': <function Chinese.talk at 0x00000236B593B6A8>}
40 {'__module__': '__main__', '__qualname__': 'Chinese', '__doc__': '\n    xxx\n    ', 'COUNTRY': 'China', 'TAG': '123', '__init__': <function Chinese.__init__ at 0x00000236B593B620>, 'talk': <function Chinese.talk at 0x00000236B593B6A8>}
41 {'__module__': '__main__', '__doc__': '\n    xxx\n    ', 'COUNTRY': 'China', 'TAG': '123', '__init__': <function Chinese.__init__ at 0x00000236B593B620>, 'talk': <function Chinese.talk at 0x00000236B593B6A8>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>}

找到数据属性,然后对数据属性进行操作,

posted @ 2018-03-28 23:05  xudachen  阅读(162)  评论(0编辑  收藏  举报