Python and factories

I don't seem to understand the correct concepts of factory.

Can someone help me write a simple test? I read some texts over the Internet and could not encode it the same way. Actually, I cannot understand this process. Copying the code is very simple, but I need to find out why this is not working.

class Factory:

    def __init__(self):
        self.msg = "teste"

    def fabricateAnotherObject(self,obj,**kwargs):
        return apply(obj,**kwargs)

class testClass:
    def __init__(self,nome,salario,endereco):
        self.nome = nome
        self.salario = salario
        self.endereco = endereco

    def __str__(self):
        return "Nome: " + str(self.nome) + "\nEndereco: " + str(self.endereco) + "\nSalario: " + str(self.salario) 

a = Factory()
emp = a.fabricateAnotherObject(testClass,"George",2000,"Three Four Five Avenue")
print str(emp)
+5
source share
4 answers

Your code is counterproductive (sorry, I have to say).

The meaning of the factory is that you do not need to know the class of your constructed object in the place where you created it.

, - . . - , - ( ), .

, 100 . , - .

factory , , .

factory :

def fabricateAnotherObject(self, **kwargs):
    return testClass(**kwargs)

, . db - . - , .

( db):

class Factory(object):
   def __init__(self, theClass):
       self.theClass = theClass
   def create(self, **kwargs):
       self.theClass(**kwargs)

myFactory = Factory(testClass)

myFactory . , myFactory - - ?

+13

Factory , ( ) (, ++ Java).

, "factory" ( ), ( , ).

Python ( ( ) ).

+4

:

    def fabricateAnotherObject(self, obj, *args):
        return apply(obj, args)

apply() . * args fabricateAnotherObject, obj , apply().

0

. type() docs.python.org/library/functions:

type (name, bas, dict)

. . - __name__; __bases__; dict - , __dict__. , :

class X(object):
    a = 1
X = type('X', (object,), dict(a=1))

( dicts), . ofc2.py.
, , ?

0

All Articles