I'm trying to catch up on Python variable annotations. According to PEP-0526 we now have something like:
class BasicStarship:
captain: str = 'Picard' # instance variable with default
damage: int # instance variable without default
stats: ClassVar[Dict[str, int]] = {} # class variable
It's been a rough weekend, and my Python is a bit rusty, but I thought variables declared without assignment to self were class variables. Here are some interesting examples:
class BasicStarship:
captain: str = 'Picard' # instance variable with default
def __init__(self,name):
self.captain = name
wtf = BasicStarship('Jim')
BasicStarship.captain = 'nope'
print(wtf.captain) #=> Jim
The above code works as I would expect. Below however confuses me a bit.
class BasicStarship:
captain: str = 'Picard' # instance variable with default
wtf = BasicStarship()
BasicStarship.captain = 'nope'
print(wtf.captain) #=> 'nope'
I would have expected 'Picard' instead of 'nope' in the second example. I feel like I am missing some rules about class variables versus instance variables. To some extent I would have thought doing BasicStarship.captain
would have resulted in a class error since the captain
is an instance variable (in the first example, not sure in the second example). Have you always been able to define instance variables after the class declaration (outside of methods)? Is there some interplay between class and instance variables that would make this clearer?
Code run with Python 3.6.3