Answer the question
In order to leave comments, you need to log in
Are class fields in Python overwritten?
I don't understand how classes work in Python.
class SimpleClass:
my_dict = {}
number = None
def return_res(self):
return self.my_dict
def __init__(self, args):
self.number = args
self.my_method()
def my_method(self):
value = self.number+10
self.my_dict.update({'key': value})
one = SimpleClass(1).return_res()
two = SimpleClass(2).return_res()
three = SimpleClass(3).return_res()
result = [one, two, three]
print(result)
[{'key': 13}, {'key': 13}, {'key': 13}]
[{'key': 11}, {'key': 12}, {'key': 13}]
Answer the question
In order to leave comments, you need to log in
You are modifying a class field, not an instance of it. You can fix it by removing the field declaration at the class level
class SimpleClass:
def __init__(self, args):
self.number = args
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question