I don’t understand how classes work in Python a bit.
class SimpleClass:

    def return_res(self):
        return self.my_dict

    def __init __(self, args):

    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]

Why would the result be like this?
[{'key': 13}, {'key': 13}, {'key': 13}]
How to get this result?
[{'key': 11}, {'key': 12}, {'key': 13}]

1 Answers 1

You modify the class field, not its instance.You can fix it by removing the field declaration at the class level
class SimpleClass:
    def __init __(self, args):
  • and what is it done for? – Gleaming Guanaco Jul 1 '19 at 11:46
  • Gleaming Guanaco, in a sense? – Ashamed Anteater Jul 1 '19 at 11:51
  • Ashamed Anteater, it is a little unclear why changes in the class property on the class itself are tied, and not on the instance instance state? – Gleaming Guanaco Jul 1 '19 at 11:52
  • How then will the method work?
    def return_res(self):
            return self.my_dict
    – Stupendous32 Jul 1 '19 at 11:53
  • Gleaming Guanaco, firstly, in Python, classes are in fact an object that defines a namespace for variables and functions declared in it, and not a language construct that describes a pattern for objects, as is done in other languages.Secondly, If you rely on analogies from other languages, then the attributes defined at the class level should be considered as static fields. – Ashamed Anteater Jul 1 '19 at 11:55
  • Stupendous32, will work fine if the my_dict attribute is also created in __ init __ – Ashamed Anteater Jul 1 '19 at 11:56
  • It seems I understood how to do it right, thanks – Stupendous32 Jul 1 '19 at 12:06