Skip to content

Commit 4ec4d1f

Browse files
committed
add python_metaclass.py
1 parent aaed9d3 commit 4ec4d1f

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
### python_decorator.py: Python进阶: 通过实例详解装饰器(附代码)
2424

2525
### python_datetime.py: 你真的了解Python中的日期时间处理吗?
26+
27+
### python_metaclass.py: Python进阶: 一步步理解Python中的元类metaclass
2628
===============================================================================
2729

2830
### 您可以fork该项目,并在修改后提交Pull request

python_metaclass.py

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

0 commit comments

Comments
 (0)