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>}

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

转载于:https://www.cnblogs.com/xudachen/p/8667034.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值