-1

For exemple in the below example:

class myClass():
    def __init__(self):
        self.A = 1.

class essai():
    def __init__(self):
        self.C = myClass()

    def ref(self):

        mystring = 'C.A'
        nameclass, nameparam = mystring.split('.')
        print(nameclass, nameparam)
        print(getattr(getattr(self,nameclass),nameparam))
        Ref = getattr(getattr(self,nameclass),nameparam)
        print(Ref)
        self.modify_val(Ref,2)
        print(self.C.A)

    def modify_val(self,x,y):
        x=y


E=essai()
E.ref()

What I would like to do is getting the reference to the attribut A of the C class in essai. The point is I would like to use that reference to update the value of C.A in the method modify_val. By using a string that contains the class and the attribute I want modify (mystring = 'C.A'), I don't understand how I can get a reference to that attribute (C.A for instance) and how I can use that reference to modify the attribute. In my example, modify_val function don't update the C.A value because Ref is not acually a reference. Therefore I get :

C A
1.0
1.0
1.0

I would like the last print to be 2

ymmx
  • 4,769
  • 5
  • 32
  • 64

1 Answers1

2

I would suggest using setattr(object, name, value)

From the python documentation for setattr

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

by passing nameclass and nameparam directly to modify_val you should be able to do something like this:

def modify_val(self, nameclass, nameparam, value)
    setattr(getattr(self,nameclass),nameparam, value)

Hope that helps.

PlikPlok
  • 110
  • 9
  • I cannot use setattr. I want update attributes of class within numba njit functions. to do so, I need to pass the reference to the attribute like I do for methods. like if i have a ref=essai.modify_val will give me a reference that I can pass to the njit function. but I cannot do this with attributes. – ymmx Mar 26 '18 at 17:41
  • Ok. I don't know about numba in particular but I found an answer talking about parameter references in python [here](https://stackoverflow.com/a/986145/2381553). It suggests to look at parameters as references all the time but some will be mutable and others immutable. – PlikPlok Mar 27 '18 at 08:09