[Solved] Would the class look like that for the object test if I change the value test.i? [closed]


If I understand your question well:

by doing test.i = "Hello", your are modifying its attribute i but your are not “modifying the class” nor its code. Your are simply changing the value of a variable that happens to be an object attribute.

So, the class “does not look like that” because it does not mean anything.

Moreover, when you change test.i after instantiating the class like you did, the value of test.o will not be changed.

See What’s the pythonic way to use getters and setters? : you can use @property to change test.o when test.i is modified.

class Test:
    def __init__(self):
        self.i = "Test"

    @property
    def o(self):
        return f"{self.i} Test"
    

test = Test()
print(test.o)  # 'Test Test'
test.i = "Hello"
print(test.o) # 'Hello Test'

Keep in mind that Python only does what YOU tell it to do. If you tell it to change the value of test.i, test.i will have the new value, but python will not modify test.o unless you tell it to do so.

With the way you defined your class, when you create a new object by doing test = Test(), Python initializes it with the value you put in __init__().

Then, when you change test.i by doing test.i = "Hello", you only change this value and not the other properties of the class.

Think about it this way : if I have an object and I modify one of its attributes, i do not want the other to be modified unless I tell Python to do so… This would be an unwanted side effect.

The @property decorator allow you to define a function and then use it as a normal attribute. In this example, test.o is re-computed each time you ask for it with the value of test.i.

Side note : those are terrible variable names…

8

solved Would the class look like that for the object test if I change the value test.i? [closed]