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?