Answer the question
In order to leave comments, you need to log in
How can you change the state of a class variable?
I have two scripts:
parent.py
class Test:
def __init__(self):
self.data = {
'name': '',
'password': ''
}
def fill_data(self):
self.data["name"] = "John"
self.data["password"] = "1234"
def change_data(self, name):
self.data["name"] = str(name)
new = Test()
if __name__ == "__main__":
new.fill_data()
time.sleep(5)
print(new.data)
from parent import new
if __name__ == "__main__":
print(f"[child]: Before change data is {new.data}") # тут должно выводится self.data = { 'name':
# 'John', 'password': '1234' }, а получается self.data = { 'name': "", 'password': "" }
setattr(new, 'name', 'Nick') # я также использовал просто new.data["name"] = "Nick"
print(f"[child]: After change data is {new.data}")
Answer the question
In order to leave comments, you need to log in
Well, nothing should have happened.
When you run child.py, you create an instance of the Test class, you have the data dictionary initialized ... That's it.
I know that you wanted the following to happen:
if __name__ == "__main__":
new.fill_data()
time.sleep(5)
print(new.data)
from parent import new
if __name__ == "__main__":
new.fill_data()
print(f"[child]: Before change data is {new.data}") # тут выведется правильная data
new.change_data('Nick')
print(f"[child]: After change data is {new.data}")
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question