2010-03-14 17 views

risposta

2

Mi piacerebbe sentire i commenti della gente su questo, ma penso che questo è un esempio di ciò che si vuole fare

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__ 

Il risultato che vedrai è: digita 'str'

+0

puoi aggiungere un po 'di "fattorizzazione" all'esempio, cioè una personalizzazione applicata agli oggetti creati? – olamundo

0

Non ce n'è bisogno. È possibile override a class's __new__() method per restituire un tipo di oggetto completamente diverso.

+0

Non penso che tu possa con metaclassi ... (forse puoi - se è così fammi sapere e avrò imparato qualcosa :)) – RyanWilcox

2

Potete trovare alcuni esempi utili a wikibooks/python, here e here

+1

quelli sono esattamente i collegamenti in cui sono incappato. Non sono riuscito a trovare un esempio concreto di fabbrica (sebbene tutti lo menzionino) in nessuno di essi ... – olamundo

Problemi correlati