Armen Avetisyan Armen Avetisyan - 14 days ago 8
Python Question

Injecting objects to class instance

I was wondering if the following is possible in python 2.7 or 3.x:

Class A:
def inject(self, **args):
... do something ...

def print(self):
print(self.x)

x = np.ones(10)
a = A()
a.inject(x)
a.print()


Note that I want
inject
to be very general and be able to add any object to the class instance.

What are your thoughts? Is this how I imagined possible?

Edit:



I also would like to inject many variables to the additional injected:

y = np.ones(10)
z = np.ones(10)
a.inject(y, z)

Answer

If I understand your question correctly then you should use setattr:

class A:
    def inject(self, name, value):
        setattr(self, name, value)

    def print(self):
        print(self.x)

x = [1, 1]
a = A()
a.inject('x', x)
a.print()
>> [1, 1]
Comments