What you probably need is to use setattr(a, "x", x).
But if you want to use this call in inject(self, name, value) function, then it might be useful to add check which would prevent overwriting an existing attribute - You might want to use if hasattr(self, name): raise AttributeError('attribute already exists') or something like that. Without this check you might be quite surprised someday what is happenning with your objects after you have accidentally overwritten attributes. Just imagine 'accidental' a.inject("inject", x) ;)
But looking at your code, you are trying to use something like 'Python-with-classes' and it looks too 'java-ish'. In Python, you do not need to define inject() and print() in your class. You can simply write:
a = object()
x = 5
setattr(a, "x", x)
print(a.x) # btw. how does your implementation `a.print()` in the question knows that attribute `x` exists?
I you want to prevent overwriting existing attributes (i.e. allow only the first injections) and still be pythonic, define your class like this:
class A(object): # note the 'object' here, it is the 'new style' class
def __setattr__(self, name, value):
if hasattr(self, name):
raise AttributeError("attribute '{}' already exists".format(name))
object.__setattr__(self, name, value)
then you can write this:
a = A()
x = 5
a.x = x
a.x = 10 # raises error
inject? You can just add an attribute to a class instance, ega.x = x.a.inject(x, y)