P
P
PR1YD2019-11-10 17:48:08
Python
PR1YD, 2019-11-10 17:48:08

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)

and child.py:
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}")

The problem is that when you try to change the new object from child.py, nothing happens. As far as I understand, this is somehow related to class instances, but my knowledge is not yet enough to figure it out myself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jottygroups, 2019-11-10
@PR1YD

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)

But it doesn't work like that. The check is false. This works if you run parent.py directly:
And even more so, you just import the variable an instance of the Test class. Even if there was a while True loop, it wouldn't execute.
You tried to access new.data['name'] from child.py via setattr, but you did it wrong. You turned to new.name, that's the error. To do everything right through setattr, it was necessary to write: The answer, how to do it right, the child.py file
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 question

Ask a Question

731 491 924 answers to any question