Chapter 12 Classes
12.2 Classes and Attributes¶
The class statement defines a custom type. Its syntax is shown in Fig. 12.1. A class statement starts with the keyword class, followed by an identifier, which specifies the name of the new type, or class, and then a semi-colon. After the class line is an indented statement block, which typically defines methods, the constructor and operators of the new type.
![Fig. 12.1 The class statement](../_images/fig12-1.jpeg)
Fig. 12.1 The class statement¶
To begin with, consider the simplest case, where a pass statement is used as the indented statement block. Such an empty type does not have any methods or operators. Nevertheless, it can be instantiated into objects, which can be assigned attributes. This simplest type of classes shows the basic way in which a custom object integrates various sources of information. Taking bank accounts for example, attributes of an account can include the name of the account holder, the account number and the balance, as shown in Table 12.1. A simplest way of defining the account type is to make it an empty class, assigning relevant attributes to its instances.
Type (account) |
Instance 1 |
Instance 2 |
---|---|---|
Account number |
100001 |
100010 |
Account holder name |
John |
Marina |
Balance |
1000 |
0 |
In the example above, the class statement defines a new type, and binds it to the identifier Account in the global binding table. Two objects, a1 and a2, are constructed, by instantiating the type via the constructor call Account(). By this step, neither a1 nor a2 hold any attributes.
Then a few attribute assignment statements are executed. Attribute assignment is similar to the assignment statement, except that the left hand side of the = sign is an attribute, rather than an identifier. The syntax of specifying an attribute in attribute assignment is:
<object >.<attribute >
Similar to the case of delitem and delslice, the del keyword can also be used to perform the delattr operation, removing an attribute from an object.
As shown by the example, after the attribute name is deleted from the object a1, a further reference to this attribute leads to an attribute error.
The assignment of attributes is object-specific rather than type-specific. For example, the attribute ‘name’ might be assigned to the account object a1 but not to a2, despite that both belong to the Account type. To avoid such inconsistencies, it is a standard practice to automatically assign all necessary attributes to an object at its construction, which is achieved by defining a custom constructor. As will be shown later, a constructor is a special method, which is executed automatically when new objects are instantiated. As a result, a new object can have an attribute automatically if the attribute is assigned in the constructor.
© Copyright 2024 GS Ng.