My understanding of the expected behaviour of a variable overwritten in a subclass is that:
- subclass().var should == the subclass.var not the baseclass.var
- type hints have no impact on Python code execution
But in the code below (abstracted from real live code):
# weird.py
from dataclasses import dataclass
@dataclass
class Base():
var = 5
def upload(self):
print('inside base')
@dataclass
class Sub(Base):
var = 10
def upload(self):
print(f"inside sub before super -> {self.var}")
super().upload()
print(f"inside sub after super -> {self.var}")
Sub().upload()
Running this:
#% python weird.py
#inside sub before super → 10
#inside base
#inside sub after super → 10
The above is what I expect.
But if I type hint var inside Base class
class Base():
var: int = 5
....
then self.var shows the Base class var value of 5 not the Sub class value of 10.
#% python weird.py
#inside sub before super → 5
#inside base
#inside sub after super → 5
I’d appreciate if someone can explain why this is so. It’s not what I would “expect”.
I’m using Python 3.11
Thank you.