forked from jackfrued/LearnPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
python_metaclass.py
55 lines (39 loc) · 1.17 KB
/
python_metaclass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# _*_ coding: utf-8 _*_
"""
python_metaclass.py by xianhu
"""
class Foo(object):
def hello(self):
print("hello world!")
return
foo = Foo()
print(type(foo)) # <class '__main__.Foo'>
print(type(foo.hello)) # <class 'method'>
print(type(Foo)) # <class 'type'>
temp = Foo # 赋值给其他变量
Foo.var = 11 # 增加参数
print(Foo) # 作为函数参数
# ========================================================================
def init(self, name):
self.name = name
return
def hello(self):
print("hello %s" % self.name)
return
Foo = type("Foo", (object,), {"__init__": init, "hello": hello, "cls_var": 10})
foo = Foo("xianhu")
print(foo.hello())
print(Foo.cls_var)
print(foo.__class__)
print(Foo.__class__)
print(type.__class__)
# ========================================================================
class Author(type):
def __new__(mcs, name, bases, dict):
# 添加作者属性
dict["author"] = "xianhu"
return super(Author, mcs).__new__(mcs, name, bases, dict)
class Foo(object, metaclass=Author):
pass
foo = Foo()
print(foo.author)