python学习 元类

 1 '''元类type的用法'''
 2 class printNum():
 3     def __init__(self,num):
 4         self.num=num
 5 
 6     def test(self):
 7         print('---{}---'.format(self.num))
 8 
 9 a=printNum(100)
10 a.test()
11 #打印结果 ---100---
12 
13 #等价于
14 def test1(self):
15     print('---{}---'.format(self.num1))
16 
17 printNum1=type('printNum1',(),{'test1':test1,'num1':200})
18 c=printNum1()
19 c.test1()
20 #打印结果 ---200---
21 
22 
23 #例子
24 def upper_attr(future_class_name,future_class_parents,future_class_attr):
25     newAttr={}
26     for name,value in future_class_attr.items():
27         if not name.startswith("__"):
28             newAttr[name.upper()]=value
29 
30     return type(future_class_name,future_class_parents,newAttr)
31 
32 #使用metaclass元类自定义类
33 class Foo(object,metaclass=upper_attr):
34     bar='bip'
35 
36 #校验Foo类是否有'bar'/'BAR'属性
37 print(hasattr(Foo,'bar'))
38 print(hasattr(Foo,'BAR'))
39 
40 f=Foo()
41 print(f.BAR)
42 
43 #打印结果
44 # False
45 # True
46 # bip

 

posted on 2019-08-11 12:28  cherry_ning  阅读(116)  评论(0)    收藏  举报

导航