Search code examples
pythonclassinstance

How to define different addresses for class attributes and instance attributes?


How to define different addresses for class attributes and instance attributes?

This problem has bothered me for a long time, unless I delete the definition of the class attribute, but want to use the class attribute.

I have defined a dict with the same name in the class attribute and instance attribute. How can I make the memory address different? I tried a variety of methods to delete the content of the class attribute. Is there any other method?

My demo code is as follows:

class MyClass:
    bar: dict = {}

    def __init__(self):
        bar: dict = {}


print(id(MyClass.bar))
a = MyClass()
print(id(a.bar))

1914627629760
1914627629760

Solution

  • class MyClass:
        bar: dict = {}
    
        def __init__(self):
            self.bar = {}
    
    
    print(id(MyClass.bar))
    a = MyClass()
    print(id(a.bar))
    
    2318292079808
    2318295104384
    

    That said, I have no idea why we are doing this, and there is an almost 100% chance this will make whomever (next) maintains this codebase go insane within the next 2 years.

    Explanation:

    You are not "saving" your variable in your __init__() function.

    Try running:

    class MyClass:
        def __init__(self):
            self.a = 1 # setting attribute a to value 1
            b = 2 # b is not an attribute, it's just a local variable
    
    m = MyClass()
    print(m.a) # this will work
    print(m.b) # this will not