Python 3home |
Introduction to Python
davidbpython.com
Class variables are data stored directly in the class; they are actually attributes set in the class.
class MyClass:
var = 10 # a class variable / attribute
val = MyClass.var # 10 (retrieve the class attribute)
MyClass.var2 = 'hello' # set an attribute directly in the class object
obj = MyClass() # MyClass instance
Instances can read class attributes using the same syntax as when reading their own attributes.
class MyClass:
var = 10 # a class variable / attribute
obj = MyClass() # a MyClass instance / object
print((obj.var)) # 10
Note that obj.var is the same syntax as the one we use to access instance attributes.
If an attribute can't be found in an object, it is searched for in the class.
class MyClass:
classval = 10 # class attribute
def __init__(self):
self.instval = 99 # instance attribute
def get(self):
return self.instval
a = MyClass()
print(a.instval) # 99 (found in the instance)
print(a.classval) # 10 (found in the class
val = a.get() # access class variable get() through the instance
Here's an example of class data that is common to each instance.
class MyClass:
instance_count = 0
def __init__(self, letter):
self.id = letter
MyClass.instance_count = MyClass.instance_count + 1
a = MyClass('alpha')
b = MyClass('beta')
print(a.id) # 'a'
print(b.id) # 'b'
print(a.instance_count) # 2
print(b.instance_count) # 2
Ex. 14.1