码迷,mamicode.com
首页 > 其他好文 > 详细

反射、元类 练习

时间:2020-04-15 17:44:33      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:count   metaclass   use   print   **kwargs   tac   单例模式   class   keyword   

‘‘‘
不会
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__)
‘‘‘

反射、元类 练习

标签:count   metaclass   use   print   **kwargs   tac   单例模式   class   keyword   

原文地址:https://www.cnblogs.com/0B0S/p/12706755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!