Variables#

Classes and their instances can contain variables (sometimes called data attributes) - it’s a peace of data that corresponds to the class or its instances.

Class and instance variables#

If variable is defined only in the class namespace - it will be a class variable, corresponding to the class. If you define an attribute using the syntax <instance name>.<attribute name> (self.<attribute name> as a particular case), it will be an attibute of the particular instance.


The following cell defines class variable MyClass.val.

class MyClass:
    val = 10

So you can work with it without creating an instance.

MyClass.val
10

But each instance will have the same attribute.

my_class = MyClass()
my_class.val
10

Even more - this is the same object.

my_class.val is MyClass.val
True

But if you access to the of the instance, it will create the new attribute that’s not realted to the attribute of the class.

my_class.val = 9
MyClass.val
10

Dynamic attributes#

There is a build-in property decorator in python that allows you to use methods just like just variable attributes of the class - the value the method returns is interpreted as the value of the corresponding attribute.


The following cell defines the RandGen class, which defines the value method under the property decorator - it just returns random values.

import random

class RandGen:
    def __init__(self, min: float, max: float):
        self.min = min
        self.max = max

    @property
    def value(self):
        return random.uniform(self.min, self.max)

The following code shows that with RandGen you can operate just like a regular variable in case of reading information.

rg = RandGen(4, 8)
[rg.value for i in range(5)]
[6.646884067379181,
 6.3595125203166845,
 7.164334806512267,
 7.855654367739249,
 7.763809778902321]

But obviously, you can’t set a new value for the attribute easily - that leads to the specific error shown in the next cell.

try:
    rg.value = 5
except Exception as e:
    print(e)
property 'value' of 'RandGen' object has no setter