python在工厂中的运用_在python中使用元类实现工厂设计模式
我很樂意聽到人們對此的評論,但我認為這是你想做什么的一個例子class FactoryMetaclassObject(type):
def __init__(cls, name, bases, attrs):
"""__init__ will happen when the metaclass is constructed:
the class object itself (not the instance of the class)"""
pass
def __call__(*args, **kw):
"""
__call__ will happen when an instance of the class (NOT metaclass)
is instantiated. For example, We can add instance methods here and they will
be added to the instance of our class and NOT as a class method
(aka: a method applied to our instance of object).
Or, if this metaclass is used as a factory, we can return a whole different
classes' instance
"""
return "hello world!"
class FactorWorker(object):
__metaclass__ = FactoryMetaclassObject
f = FactorWorker()
print f.__class__
您將看到的結果是:鍵入'str'
總結
以上是生活随笔為你收集整理的python在工厂中的运用_在python中使用元类实现工厂设计模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python cursor游标_第二十三
- 下一篇: 大家对Java的一些误解