0

What is the correct way to update instance attributes? If I have an attribute that depends on another attribute, how do I update the dependent attribute after the first one was changed?

How would I achieve the desired output below?

For example, I create a class with 2 attributes, name and file_path. If I change self.name and want self.file_path to change as well, how would I do that?

class TestClass:
    def __init__(self):
        self.name = "the_file"
        self.file_path = f'folder/subfolder/{self.name}'

    def show_filepath(self):
        print(self.file_path)


test = TestClass()
print(test.name)
print(test.file_path)
test.show_filepath()

#update the name
test.name = "new_name"
print("after update")
print(test.name)
print(test.file_path)
test.show_filepath()

Output:

> the_file
> folder/subfolder/the_file
> folder/subfolder/the_file
> after update
> new_name
> folder/subfolder/the_file
> folder/subfolder/the_file

Desired output:

> the_file
> folder/subfolder/the_file
> folder/subfolder/the_file
> after update
> new_name
> folder/subfolder/new_name
> folder/subfolder/new_name

Are there reasons why it behaves this way?

khelwood
  • 55,782
  • 14
  • 81
  • 108
TheRibosome
  • 301
  • 1
  • 9
  • 1
    "I assume there is reasons why it behaves this way?" Yes, that is jus the basic semantics of Python. There's no reason to expect updating `name` would affect `file_path`. – juanpa.arrivillaga Jun 07 '22 at 08:12
  • `f'folder/subfolder/{self.name}'` is evaluated _once_. If you want changes to one attribute to alter another, look into _properties_. – jonrsharpe Jun 07 '22 at 08:12
  • You seem to be using instance attributes, not class attributes. – khelwood Jun 07 '22 at 08:12
  • So you need to decide how users will interact with the state of your class. The basic approach would be to use a method to set these attributes. This coudl also be done using a `property`, if your class is already in use and `test.name = whatever` was the way you were expecting the class to be used, the point is - you have to implement this somehow – juanpa.arrivillaga Jun 07 '22 at 08:16

0 Answers0