add python_metaclass.py

master
xianhu 2016-11-23 17:11:12 +08:00
parent aaed9d3441
commit 4ec4d1ffc8
2 changed files with 57 additions and 0 deletions

View File

@ -23,6 +23,8 @@
### python_decorator.py: Python进阶: 通过实例详解装饰器(附代码)
### python_datetime.py: 你真的了解Python中的日期时间处理吗
### python_metaclass.py: Python进阶: 一步步理解Python中的元类metaclass
===============================================================================
### 您可以fork该项目,并在修改后提交Pull request

View File

@ -0,0 +1,55 @@
# _*_ coding: utf-8 _*_
"""
python_metaclass.py by xianhu
"""
class Foo:
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)