#๐Ÿ”’ Difference between static class members and instance variables

10 messages ยท Page 1 of 1 (latest)

mighty raven
#

I was looking at something that looked like:

class T:
   xs : List[int]
   ys : List[int] = []
   i : int
   i_g : int = 0

  def __init__(self, xs: List[int], ys: List[int]):
    self.xs = xs
    self.ys = ys
    self.i = 0

And I was just wondering if the variables declared at class level are static class members or if they're provided as type inference for instance variables and does providing a default value differenciate between the two (for example, since i_g is provided the default value, does that make it a static and if so, is it possible to provide a default value to instance variables)?

balmy steepleBOT
#

@mighty raven

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

deft bronze
#

They are static and live directly inside the T class object, you can say T.ys to access the list you initialised in the class itself

#

Instances that have a self.ys instance attribute assigned will then shadow that class attribute

#

As for type inference, there is no coercion and type checking only happens at IDE-level, if you run python code without an IDE you can have wildly mismatched types and the code won't complain

#

But yes i'd imagine IDEs use it for typing

mighty raven
#

I see, this lines up with what I originally thought - just that I was reading https://peps.python.org/pep-0526/#class-and-instance-variable-annotations and it seems to be saying that in order to declare static variables you need to designate it with ClassVar.

storm sigil
#

(and yes you can provide defaults for instance variables but that's done in the constructor signature not anything to do with the class attributes)

balmy steepleBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.