Python: variables in the class scope are class, not instance
Posted by jpluimers on 2019/09/03
A very subtle thing that keeps biting me as my background is from languages where by default, identifiers on the class scope are instance level, not class level:
In Python, variables on class level are class variables.
If you need instance variables, initialise them in your constructor with a
self.variable = value.
The example in the Python 3 docs [WayBack] Classes – A First Look at Classes – Class and Instance Variables is the same as in the Python 2 docs [WayBack] Classes – A First Look at Classes – Class and Instance Variables:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:
class Dog: kind = 'canine' # class variable shared by all instances def __init__(self, name): self.name = name # instance variable unique to each instance >>> d = Dog('Fido') >>> e = Dog('Buddy') >>> d.kind # shared by all dogs 'canine' >>> e.kind # shared by all dogs 'canine' >>> d.name # unique to d 'Fido' >>> e.name # unique to e 'Buddy'
For people new at Python: the __init__ is a constructor; see these links for more explanation:
- [WayBack] Python __init__ and self what do they do?
- Python 3 [WayBack] Classes – A First Look at Classes – Class Objects / Python 2 [WayBack] Classes – A First Look at Classes – Class Objects
Of course, the
__init__()method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to__init__(). For example,>>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)
–jeroen






Leave a comment