So far we have learned how to create classes and how to create objects as class instances. However, the functionality of these classes as well as objects is useless. To add some functionality is to add some attributes to the objects. The object attributes are added outside the class so in this case, we don't have to do any modifications to the body class.
So how do assign attributes to the object? Let's start by class definition and creating an object.
Example 1 Create Rectangle class and instantiate two objects "Small" and "Large" of the Rectangle class. Then assign attributes 4 and 5 to the "Small" object and assign 10 and 20 values to the attributes of the "Large" class.
class ClassName:The general form of creating an object attribute can be written as:
"ClassBody"
Object = ClassName()
Object.Attribute = valueThe previous code is a dot notation and is used to assign value to an attribute on an Object1. The value of an attribute can be any data type i.e. Python primitive, built-in data type, or another object, function, or class. In the following example, we will create a class Rectangle, instantiate two class objects and add some attributes to these objects.
Example 1 Create Rectangle class and instantiate two objects "Small" and "Large" of the Rectangle class. Then assign attributes 4 and 5 to the "Small" object and assign 10 and 20 values to the attributes of the "Large" class.
class Rectangle:The output of Example 1.
pass
Small = Rectangle()
Large = Rectangle()
Small.a = 4
Small.b = 5
Large.a = 10
Large.b = 20
print("Small.a = {}; Small.b = {}".format(Small.a, Small.b))
print("Large.a = {}; Large.b = {}".format(Large.a, Large.b))
Small.a = 4; Small.b = 5
Large.a = 10; Large.b = 20