cherry-ning

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

 

分类:

技术点:

相关文章:

  • 2021-08-18
  • 2022-02-09
  • 2021-05-03
  • 2021-06-14
  • 2021-11-24
  • 2022-12-23
  • 2021-11-21
猜你喜欢
  • 2021-05-10
  • 2021-11-21
  • 2021-08-26
  • 2021-12-27
  • 2021-08-30
  • 2022-03-07
  • 2021-04-05
相关资源
相似解决方案