Python 3

home

Introduction to Python

davidbpython.com




Class Variables / Attributes


class variables / attributes

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






class variables / attributes are also accessible through its instances

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.






<object>.<attribute> 'cascading' lookup

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






class variable is shared data for instances

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





[pr]