# -*- coding:utf-8 -*-
class Demo(object):
def __init__(self, *args):
super(Demo, self).__init__(*args)
if __name__ == '__main__':
print(Demo.__class__)
#output : <class 'type'>
上面的输出为type ,这个意思是这个类的创建工厂是type, Python 中所有的东西都是type ,他是所有对象的祖宗。
那我们是不是可以修改这个祖先,答案是肯定可以的,所有就有了metaclass 这个东西,
首先我们先创建一个祖先
class MetaStr(type):
def __new__(cls, name, base ,dct):
assert '__str__' in dct.keys(),'you must define a __str__ method'
# 也可以添加属性
dct['all'] = cls.all()
return super(MetaStr,cls).__new__(cls, name, base ,dct)
def all():
print('all')
创建几个类使用这个祖先
class Foo(object, metaclass=MetaStr): pass
class Demo(object,metaclass=MetaStr):
# py 3 使用metacless 关键字
# py2 __metaclass__
def __str__(self):
print('__str__ method')
def test(self):
print('test method ')
实例化类来测试:
# foo = Foo()
# foo.all()
#output AssertionError: you must define a __str__ method
demo = Demo()
demo.all()
可以发现 给demo 这个实例已经动态的添加了一个新的属性call ,
同时可以确保所有的子类都实现了__str__ 方法
我们可以使用metaclass 来动态控制各种类的生成,
如果有兴趣你可以查看:
https://stackoverflow.com/que...
这个具有
1503 个start 的问题。