2

I have a class with some class attributes

class Test:
    attr = {#lots of data}


class Sub(Test):
    def __init__(self, param):
        self.param = param

Now if I initialize lots of subclasses [Sub(i) for i in range(10000)] each instance of Sub will have an attribute attr. Does that copy the data in attr 10000 times or does each reference of attr point to the same dictionary?

Edit:

Could someone also explain this behavior if attr is a class attribute and the data does not get copied, what exactly happens here

test1 = Sub(1)
test2 = Sub(2)
test1.attr == test2.attr. # True

test1.attr = {}
test1.attr == test2.attr  # False

I was expecting that assigning an empty dictionary to the attr in the instance would overwrite the reference to the class attribute for all instances but that is not the case

6
  • 3
    attr is class attribute. No copy is done when Sub(i) is created. Commented Apr 7, 2021 at 19:52
  • Gotcha, what happens when you overwrite the class attribute in the instance? It doesn't seem to affect the class attribute in other instances Commented Apr 7, 2021 at 20:01
  • 1
    When you overwrite the attribute of an instance it only affects that instance. If you update the attribute, eg test1.attr['foo'] = 0, then all instances see the update. Commented Apr 7, 2021 at 20:04
  • 1
    You could also confirm this using the following: Sub(1).attr is Sub(1).attr # (is True) and Sub(1).param is Sub(2).param # (is False). Commented Apr 7, 2021 at 20:04
  • 1
    Check out Is Python class variable static? Commented Apr 7, 2021 at 20:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.