Z
Z
zybzick2019-07-01 10:37:13
Python
zybzick, 2019-07-01 10:37:13

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)

Why would the result be like this? How to get such a 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

1 answer(s)
S
Sergey Gornostaev, 2019-07-01
@zybzick

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 question

Ask a Question

731 491 924 answers to any question