CHAPTER 12
Working with Classes
In this chapter, you work with Python’s classes, which enable you to create custom objects in your scripts. You learn to create a class, create objects based on that class, and work with those objects. Because of the nature of classes, this chapter is set up as an extended example using Visual Studio Code rather than terminal windows, and we recommend you work through the chapter from start to end.
Understanding Classes and Instances
Create a Class and Instantiate Instances
Understanding Class and Instance Attributes
Set Class and Instance Attributes
Understanding Classes and Instances
In Python, a class is a template for creating objects of a particular type — a “class” of object, in computer terms. When you need to create standardized objects of the same type, you can declare a class for that type of object. You can then create what are called instances of the class — individual objects based on the class.
In this chapter, you create a class called BranchOffice
to use for creating objects that store data on the individual branch offices of a notional company. After creating the class, you can create a separate instance for each branch office.
When Should You Create a Class?
Consider creating a class when you need to create consistent objects of a type that Python itself does not provide.
Classes are especially useful for encapsulation, using a single object both to store data and to provide functionality for manipulating that data. Creating a class makes encapsulation easy, as you can define attributes to store the data and construct methods to provide the necessary functionality.
How Do You Create a Class?
You create a class by using a class header statement. The class header begins with the class
keyword. Next, it provides the name you want to give the class. Like other headers, the class header ends with a colon, after which the statements that belong to the class definition are indented by four spaces.
For example, the following class header creates the class called BranchOffice
. The second statement, pass
, is a placeholder indicating where code for the class will appear. As with other Python structures, the code for the class is indented by four spaces beyond the class header.
class BranchOffice:
pass
How Are Python Class Names Usually Capitalized?
Python convention is to use a capital letter at the start of each word in the class — for example, BranchOffice
. This capitalization style is sometimes called Pascal Case, named after the programming language Pascal, which in turn was named after the French mathematician and philosopher Blaise Pascal.
How Do You Create an Instance of a Class?
After creating a class, you can create an instance of the class, an object based on the class. Creating an instance is sometimes referred to as instantiating the instance.
To create an instance, you create a variable and assign an object based on the class. The following statement creates a variable named a
and assigns to it an instance of the BranchOffice
class:
a = BranchOffice()
The illustration shows the relationship between a class and instances of that class.
Create a Class and Instantiate Instances
In this section, you create the BranchOffice
class, giving it the absolute minimum of code required for Python to run it without raising errors. You then create two instances of the BranchOffice
class, verify their class type using the type
function, and compare the two instances to prove that they are not the same object.
Because this chapter presents an extended example, we recommend you work in Visual Studio Code rather than in a terminal window. Using Visual Studio Code enables you to return easily to the code you have written so far and make changes to it without extensive retyping.
Create a Class and Instantiate Instances
Open Visual Studio Code and create a new Python script.
Type the following statement, which creates the BranchOffice
class, and then press :
class BranchOffice:
Visual Studio Code automatically indents the next line.
Type the following pass
statement, which enables Python to run the class code without raising an error. Press twice.
pass
Type the following statement, which creates a variable named a
and assigns to it an instance of the BranchOffice
class. Press .
a = BranchOffice()
Type the following statement, which creates a variable named b
and assigns to it another instance of the BranchOffice
class. Press .
b = BranchOffice()
Type the following statement, which uses the type
function to retrieve the type of a
and the print()
function to display the result. Press .
print(type(a))
Type the following statement, which uses the type
function to retrieve the type of b
and the print()
function to display the result. Press .
print(type(b))
Type the following statement, which uses the print()
statement to display the result of comparing a
and b
. Press .
print(a == b)
Click Run Python File in Terminal ().
The Terminal pane appears.
Python displays the object types of a
and b
. Each object is of the following type:
<class '__main__.BranchOffice'>
Python displays False
as the result of the a == b
comparison. This indicates that a
and b
are not the same object, even though they are of the same object type. Similarly, if you have two quarters in your pocket, they are equal in that they have the same value, but they are separate coins, not the same coin.
Understanding Class and Instance Attributes
Once you have created a class, Python enables you to set two types of attributes related to it: class attributes and instance attributes. In this section, you learn the difference between class attributes and instance attributes and how to create both types. You also learn about the __init__()
method of the class object, a special method that runs automatically when you create a new instance from a class, and the self
keyword, which Python uses to refer in code to an object itself.
Given that a class is a template that defines an object type and that an instance of a class is an object that uses that class as its template, you can quickly grasp the difference between class attributes and instance attributes.
Understanding How You Set Class Attributes
To set a class attribute, you place a statement in the class definition block. After the class header and indented by four spaces as usual, you create a variable for the attribute and then assign the appropriate data to it.
For example, the following statements show the BranchOffice
class header followed by a statement that creates the variable company
and assigns to it a company name.
class BranchOffice:
company = "CheeseWheat Associates"
Understanding How You Set Instance Attributes
To set an instance attribute, you use the __init__()
method of the class object. After the class header, and indented by four spaces, place the header for the __init__()
method. The header consists of the def
keyword, the __init__()
name, the self
parameter, and the name of each instance attribute you want to set. For example, the following method header provides the names address
and manager
:
class BranchOffice:
def __init__(self, address, manager):
The self
parameter refers to the current instance of the class — the instance that is being initialized by the __init__()
method. The word self
is the default term for this parameter, and it is usually easiest to use self
. However, you can use a different word instead of self
if you prefer. No matter which word you use, you must supply it as the first parameter of any function you define in the class.
After specifying the names of the instance attributes in the __init__()
method header, you can set the values for these attributes, as in the following example:
class BranchOffice:
def __init__(self, address, manager):
self.address = address
self.manager = manager
Set Class and Instance Attributes
In this section, you extend the BranchOffice
class by setting class attributes and instance attributes for it. To set the class attributes, you include statements in the class definition block. To set the instance attributes, you add code for the class’s __init__()
method. The method’s name has two underscores before it and two after it.
The class attributes for the BranchOffice
class are company
and sector
. The instance attributes for the instances of the BranchOffice
class are manager
, street
, city
, state
, and zip
.
Set Class and Instance Attributes
In Visual Studio Code, open the script you created earlier.
Double-click the pass
statement in line 2 to select it, and then type over it the following statement, which creates the variable company
and assigns to it the company name. Press .
company = "CheeseWheat Associates"
Note: When you replace the pass
statement, make sure you maintain the indentation for the company
statement.
Type the following statement, which creates the variable sector
and assigns a string to it. Press .
sector = "food science"
Type the following statement, which uses the def
keyword to create the __init__()
method for the class. The statement gives self
as the required first argument and adds five instance attributes: city
, street
, state
, zip
, and manager
. Press .
def __init__(self, city, street, state, zip, manager):
Note: Type two underscores before init
and two after it.
Type the following statement, which assigns to the city
attribute of the self
object the value passed by the city
argument in the call to initialize the class. Press .
self.city = city
Type the following four statements, which similarly populate the street
, state
, zip
, and manager
attributes of the self
object. Press at the end of each line.
self.street = street
self.state = state
self.zip = zip
self.manager = manager
Click inside the parentheses of the a = BranchOffice()
statement, and then type in strings for the five instance attributes.
a = BranchOffice("Arcata", "442 Front", "CA", "95521-1111", "Aurora Smith")
Note: You do not need to provide a value for the self
attribute.
Repeat step 7 for the b = BranchOffice()
statement:
b = BranchOffice("Blythe", "6 Lincoln", "CA", "92225-1234", "Art Kimura")
Select the five print()
statements, and then type over them the five following statements, pressing at the end of each line:
print(a.manager)
print(a.street)
print(a.city)
print(a.state)
print(a.zip)
Click Run Python File in Terminal ().
The Terminal pane opens.
Python displays the information from the instance attributes of the a
object.
Grasp Class, Instance, and Static Methods
A method is a unit of code that performs an action on an object. A method is similar to a function, but it is bound to a particular object rather than being globally available. Python enables you to create and use three different types of methods within a class: class methods, instance methods, and static methods. In this section, you learn how these three types of methods work and how they differ from each other. You also learn how and when to use each type of method.
A class can contain class methods, instance methods, and static methods. You create any methods needed when you define the class, including the methods’ code as part of the class definition.
Class Methods
A class method belongs to the class object that declares it. A class method can access only data within the class itself, not data within any particular instance of the class. A class method can change the data in the class.
You would create a class method to take action in the class, such as changing the class’s state.
Instance Methods
An instance method belongs to a particular instance created from the class object that declares the method. An instance method can access data within that instance, but it cannot access data within other instances created from the same class object. An instance method can also access data within the class itself by using the self.__class__
attribute.
You would create an instance method to take action within a particular instance of the class, accessing data from within the class itself if necessary.
Static Methods
A static method is bound to the class that declares it but cannot change the data in the class; it also cannot access, let alone change, the data in an instance based on the class. A static method is similar to a function except that it belongs to the class’s namespace and becomes available only when you create the class.
You would create a static method to add functionality that was needed only when the class or an instance of the class was active and that did not require access to the data of either the class or the instance.
Which Type of Method Should You Use in Your Classes?
Generally speaking, instance methods are the most widely useful of the three types of methods bound to classes, because an instance method can manipulate data either in its own instance or in the class on which the instance is based. By contrast, a class method can manipulate data only in its own class; and a static method cannot even access data within its own class, though it can perform other actions freely.
When you create a method inside a class definition, Python makes the method an instance method by default. You can change the method to a class method or an instance method if necessary.
The following sections show you how to create and call instance methods, class methods, and static methods.
Create an Instance Method
To create an instance method, you place code inside the class definition. The first line of the instance method is the method head, which consists of the def
keyword, the method name, parentheses containing the required parameter self
and any other parameters, and a colon. For example, the first of the following statements starts the class definition, the second is a comment, and the third contains the method header for an instance method called getManagerName
:
class BranchOffice():
# the def __init__ function appears here
def getManagerName(self):
After the method header, you include the statements for the method, indented by four spaces. Here is an example:
class BranchOffice():
# the def __init__ function appears here
def getManagerName(self):
mgr = f"{self.city} Office Manager: {self.manager}"
return mgr
Call an Instance Method
You can call an instance method only from an instance of the class. For example, the first of the following statements creates a variable named c
and assigns to it an instance of our BranchOffice
class. The second statement calls the getManagerName()
method and displays the resulting information.
c = BranchOffice("City of Industry", "1810 Elm", "CA", "91748-0019", "Ri Zhang")
print(c.getManagerName())
Python provides two different ways of creating class methods and static methods. The first way is to use the @classmethod
decorator for a class method or the @staticmethod
decorator for a static method. The second way is to use the classmethod()
method or the staticmethod()
method. Both ways work, and you should know how to use them, because you may encounter them in code. However, the classmethod()
method and staticmethod()
method are considered “un-Pythonic,” and using the decorators is considered better practice.
Create a Class Method
To create a class method, you place code inside the class definition, as for an instance method. But before the method header for the class method, you place the @classmethod
decorator. This decorator tells Python to turn the method into a class method.
For example, the first of the following statements starts the class definition, and the second is a comment, as before. The third statement supplies the @classmethod
decorator. The fourth statement is the method header for the showClassInfo
method. The fifth line is the method’s only statement, setting it to return a string including self.company
, the company
attribute of the class object.
class BranchOffice():
# the def __init__ function appears here
@classmethod
def showClassInfo(self):
return "Company Name: " + self.company
You can also create a class method by using the classmethod()
method to return a class method from an instance method. For example, if you have created an instance method called info()
in the BranchOffice
class, you can create a class method of info()
like this:
BranchOffice.info = classmethod(BranchOffice.info)
You can then call the info()
method through the BranchOffice
class like this:
BranchOffice.info()
Call a Class Method
You can call a class method either from the class itself or from an instance of the class.
From the class, use the class name followed by a period and the method name, like this:
print(BranchOffice.showClassInfo())
From an instance of the class, use the instance name followed by a period and the method name. For example, if you have created an instance called c
, you can call the class method like this:
print(c.showClassInfo())
Create a Static Method
You create a static method in a similar way to a class method: You place the method’s code inside the class definition, but you precede it with the @staticmethod
decorator, which tells Python to turn the method into a static method.
For example, the first statement shown in the following code block starts the class definition, the second contains a comment, and the third provides the @staticmethod
decorator. The fourth statement is the method header for the cm2cf
method, which returns the approximate number of cubic feet for the number of cubic meters specified by the m3
parameter. The fifth line is the method’s only statement, setting it to return m3
multiplied by 35.3
, the number of cubic feet in a cubic meter.
class BranchOffice():
# the def __init__ function appears here
@staticmethod
def cm2cf(m3):
return m3 * 35.3
As with a class method, you can create a static method by using the staticmethod()
method to return a static method from an instance method. For example, if you have created an instance method called convert()
in the BranchOffice
class, you can create a static method of convert()
like this:
BranchOffice.convert = staticmethod(BranchOffice.convert)
Call a Static Method
To call a static method, you call it either via the class name and the method name or via the object name and the method name.
For example, say you have instantiated an object called office1
of the BranchOffice
class. The class includes the static method jp
. You can call the static method via the class like this:
BranchOffice.jp()
Or you can call the static method via the object like this:
office1.jp()
Create an Instance Method
In this section, you create an instance method called getInfo()
in the BranchOffice
class. This instance method pulls information from the instance’s attributes, such as the city
attribute and the manager
attribute, so that it can return an f-string containing information about the branch office the instance represents.
In an instance method, the first parameter refers to the instance itself. The default term for this parameter is self
; it is generally easiest and clearest to use self
, but you can use a different term instead if you prefer.
Create an Instance Method
In Visual Studio Code, open the Python script for your class.
Click the line after the end of the __init__()
method, press to apply a four-space indent, and type the following statement, which declares the getInfo()
method and gives it the required self
parameter. Press .
def getInfo(self):
Python automatically indents the next line one step further.
Type the following statement, which creates the variable br
and begins assigning to it a group of f-strings that pull information from the instance attributes and combine it with static text. Press at the end of each line.
br = (
f"{self.city} Office
"
Type the following three statements, which add to the group of f-strings:
f"Manager: {self.manager}
"
f"{self.street}
"
f"{self.city}, {self.state} {self.zip}"
)
Press to unindent one step, and then type the following return statement, which returns br
:
return br
Select the five print()
statements, and type the following print()
statement over them:
print(a.getInfo())
Click Run Python File in Terminal ().
The Terminal pane opens.
Python displays the branch office information.
Create a Class Method
In this section, you create a class method called showClassInfo()
in the BranchOffice
class. This class method returns the class’s company
attribute and sector
attribute and places them in an f-string that it returns to the code that called it.
To create the class method, this section uses the @classmethod
decorator rather than the classmethod()
method. The first parameter in the class header refers to the class itself. This section uses the default term for this parameter, self
, but you can use a different term if you like.
Create a Class Method
In Visual Studio Code, open the Python script for your class.
Click after the sector = "food science"
line, and then press to create a new line.
Type the following @classmethod
decorator, and then press :
@classmethod
Type the following method header, and then press :
def showClassInfo(self):
Visual Studio Code indents the next line automatically.
Type the following two statements, which create a variable named ci
and assign to it the class’s company
attribute and sector
attribute plus some linking text. Press .
ci = self.company + ", a "
ci = ci + self.sector + " trendsetter"
Type the following statement, which ends the method and returns ci
. Press .
return ci
At the end of the script, edit the print()
statement to the following:
print(BranchOffice.showClassInfo())
Click Run Python File in Terminal ().
The Terminal pane opens.
The class method displays the class information.
Create a Static Method
In this section, you create a static method in the BranchOffice
class. The method is called cm2cf()
and converts cubic meters to cubic feet. The method takes a single argument, m3
, which gives the number of cubic meters, and returns the corresponding number of cubic feet. Because a static method accesses neither the class nor any instance of it, it does not use the self
parameter.
This section uses the @staticmethod
decorator rather than the staticmethod()
method to tell Python to create the static method.
Create a Static Method
In Visual Studio Code, open the Python script for your class.
Click on the blank line following the return br
statement at the end of the getInfo()
method, and then press to indent the line by one step.
Type the following @staticmethod
decorator, and then press :
@staticmethod
Type the following method header, and then press :
def cm2cf(m3):
Python indents the next line by another step.
Type the following return
statement, which returns a string including the m3
value multiplied by 35.3
and lightly rounded. Press twice.
return str(round(m3 * 35.3, 1)) + " cubic feet"
At the end of the script, change the print()
statement to the following, which prompts the user to enter the number of cubic meters, converts the resulting string to a float, passes it to the cm2cf
method, and displays the result.
print(BranchOffice.cm2cf(float(input("Enter the number of cubic meters: "))))
Click Run Python File in Terminal ().
The Terminal pane opens.
Type the input number and press .
The result appears.
Review the Class’s Code
This section presents the code for the class you have created in this chapter. The class starts with the class definition (A), followed by statements defining the class attributes company
(B) and sector
(C). The @classmethod
decorator (D) precedes the showClassInfo()
class method. The __init__()
method (E) declares and populates variables for each new instance of the class. The getInfo()
instance method (F) displays information about a particular instance. The @staticmethod
decorator (G) introduces the cm2cf()
static method, which converts cubic meters to cubic feet. The code then instantiates two instances (H) of the class, and the print()
statement (I) displays information.
3.142.90.235