0

So from what I understand, in Python class variables are like static variables in C++ and instance variables are like regular member variables. And https://docs.python.org/3/library/typing.html says

class Starship:
    stats: ClassVar[dict[str, int]] = {} # class variable
    damage: int = 10                     # instance variable

so the line with 'damage' shows how to add typing to a variable that is to be used as an instance variable, i.e. each object has its own copy and when a new Starship is made, 'damage' is initialized to 10 for each of them (I think).

But then, why does

class A():
    a : {} = {}

l = []

for i in range(2):
    a = A()
    a.a["a"] = i
    l.append(a)

print(l[0].a)
print(l[1].a)

print

{'a': 1}
{'a': 1}

and not

{'a': 0}
{'a': 1}

as I would expect? I know that I could just initialize the instance variable in __ init __() but I want to add typing to my instance variables. Thanks.

Roel
  • 19,338
  • 6
  • 61
  • 90
  • That `Starship` example is only about type annotations, it does not change how the attributes themselves behave. It's a slightly misleading example, since it's implicit that you'd do `ss = Starship(); ss.damage = 50`, which makes `damage` an instance attribute. The `ClassVar` annotation is explicitly to annotate that that attribute will *not* be shadowed by instance attributes and that it would be a type error to do so. Which BTW is further explained in that `Starship` section in the documentation. – deceze Nov 14 '20 at 13:30
  • 1
    @Roel Hope [this](https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations) helps. It has an example which explains *how to annotate instance variable* – Abdul Niyas P M Nov 14 '20 at 13:41
  • @AbdulNiyasPM Thank you, that actually answers the question I was asking. – Roel Nov 14 '20 at 14:01

0 Answers0