2010-03-14 55 views

回答

2

我很想聽聽人們對這個意見,但我認爲這是你想要做

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__ 
內容示例

你會看到的結果是:type'str'

+0

您能否在示例中添加一點「重要性」,即將一些自定義應用於創建的對象? – olamundo 2010-03-14 21:03:02

0

沒有必要。你可以override a class's __new__() method爲了返回一個完全不同的對象類型。

+0

我不認爲你可以用元類...(也許你可以 - 如果讓我知道,我會學到一些東西:)) – RyanWilcox 2010-03-14 20:52:44

2

你可以找到wikibooks/pythonherehere一些有用的例子

+1

這些都是確切的我偶然發現的鏈接。我找不到一個工廠的具體例子(雖然他們都提到了它)... – olamundo 2010-03-14 21:01:37