11.2: Classes and Instances
- Page ID
- 117593
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\dsum}{\displaystyle\sum\limits} \)
\( \newcommand{\dint}{\displaystyle\int\limits} \)
\( \newcommand{\dlim}{\displaystyle\lim\limits} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\(\newcommand{\longvect}{\overrightarrow}\)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)By the end of this section you should be able to
- Create a class with instance attributes, class attributes, and the
__init__()method. - Use a class definition to create class instances to represent objects.
Classes and instances
In the previous section, a real-world entity, like a person's social media profile, was modeled as a single object. How could a programmer develop a software system that manages millions of profiles? A blueprint that defines the fields and procedures of a profile would be crucial.
In a Python program, a class defines a type of object with attributes (fields) and methods (procedures). A class is a blueprint for creating objects. Individual objects created of the class type are called instances.
Consider the example below:
class Cat:
def __init__(self):
self.name = 'Kitty'
self.breed = 'domestic short hair'
self.age = 1
def print_info(self):
print(self.name, 'is a ', self.age, 'yr old', self.breed)
pet_1 = Cat()
pet_2 = Cat()
What is the name of the class?
Catclass Catself
- Answer
-
a.
Catfollows the class keyword at the top of the class definition and is the name of the class.
Which of the following is an instance of the Cat class?
__init__namepet_1
- Answer
-
c.
pet_1is an instance of theCatclass created by callingCat(). The other instance ispet_2.
Which of the following is an attribute?
breedpet_2print_info
- Answer
-
a.
breedis an instance attribute definedin __init__(). The other instance attributes arenameandage.
Suppose the programmer wanted to change the class to represent a pet cat. Which is the appropriate name that follows PEP 8 recommendations?
petcatpet_catPetCat
- Answer
-
c.
CapWordsstyle, with all words capitalized and no spaces between words, is recommended for class names. "Pet" and "cat" are separate words, so each is capitalized and one directly follows the other.
Creating instances with __init__()
___init___() is a special method that is called every time a new instance of a class is created. self refers to the instance of a class and is used in class methods to access the specific instance that called the method. __init__() uses self to define and initialize the instance's attributes.
Consider the example below:
1
class Rectangle:
def __init__(self):
self.length = 1
self.width = 1
def area(self):
return self.length * self.width
room_1 = Rectangle()
room_1.length = 10
room_1.width = 15
print("Room 1's area:", room_1.area())
room_3 = Rectangle()
room_3.length = 12
room_3.width = 14
print("Room 3's area:", room_3.area())
How many times is __init__() called?
- 1
- 2
- 3
- Answer
-
b. Two instances,
room_1androom_3, are created by callingRectangle(), which calls the constructor__init__().
When line 11 executes, execution flow moves to line 5. What does self represent on line 5?
- the area of
room_1 - the instance
room_1 - the
Rectangleclass
- Answer
-
b.
room_1is the instance that called the methodarea(), soselfrepresents the specific instance.
Which line initializes the instance attribute length?
- 3
- 6
- 9
- Answer
-
a. Line 3 is in
__init__(), which initializes length and the other instance attributes for each new instance.
Suppose line 2 is changed to def __init__():. What would room_1's attributes be initialized to?
length = 0,width = 0length = 1,width = 1Error
- Answer
-
c.
__init__()has one required parameter, conventionally calledself, which allows the constructor to access the instance.
Instance attributes vs. class attributes
The attributes shown so far have been instance attributes. An instance attribute is a variable that is unique to each instance of a class and is accessed using the format instance_name.attribute_name. Another type of attribute, a class attribute, belongs to the class and is shared by all class instances. Class attributes are accessed using the format class_name.attribute_name.
Consider the example above.
Which is an instance attribute?
locorder_idorder_3
- Answer
-
b.
order_idis an instance attribute defined in__init__(). The other instance attribute iscup_size.
Suppose the line order_1.cup_size = 8 is added before order_3.print_order(). What is the new output?
Cafe Coffee Order 3 : 8 ozCafe Coffee Order 3 : 16 ozError
- Answer
-
b. Changing
order_1.cup_sizedoes not affectorder_3.cup_size. order_1.cup_sizechanges to8andorder_3.cup_sizeis still16.
Suppose the line CoffeeOrder.loc = 'Caffeine Cafe' is added before order_3.print_order(). What is the new output?
Caffeine Cafe Order 3 : 16 ozCafe Coffee Order 3 : 16 ozError
- Answer
-
a.
order_1,order_2, andorder_3all share the class attributeCoffeeOrder.loc. Changinglocaffects all instances, soCaffeine Cafeis printed as the location.
Suppose the line self.cls_id = 5 is added to the end of __init__()'s definition. What is the new output?
Cafe Coffee Order 5 : 16 ozCafe Coffee Order 3 : 16 ozError
- Answer
-
b. Trying to access a class attribute using an instance is unsafe. In
__init__(), trying to access the class attribute creates a new instance attribute calledcls_id. Though possible, programmers should avoid using the same name for class attributes and instance attributes to avoid confusion.
Write a class, FlightTicket, as described below. Default values follow the attributes. Then create a flight ticket and assign each instance attribute with values read from input.
Instance attributes:
- flight_num: 1
- airport: JFK
- gate: T1-1
- time: 8:00
- seat: 1A
- passenger: unknown
Class attributes:
- airline: Oceanic Airlines
- airline_code: OA
Method:
__init__(): initializes the instance attributesprint_info(): prints ticket information (provided in template)
Given input:
2121
KEF
D22B
11:45
12B
Jules Laurent
The output is:
Passenger Jules Laurent departs on flight # 2121 at 11:45 from KEF D22B in seat 12B
Write a class, Book, as described below. Then create two instances and assign each instance attribute with values read from input.
Instance attributes:
- title: ''
- author: ''
- year: 0
- pages: 0
Class attribute:
- imprint: Fantasy Tomes
Method:
__init__(): initializes the instance attributesprint_info(): prints book information (provided in template)
Given input:
Lord of the Bracelets
Blake R. R. Brown
1999
423
A Match of Thrones
Terry R. R. Thomas
2020
761
The output is:
Lord of the Bracelets by Blake R. R. Brown published by Fantasy Tomes
in 1999 with 423 pages
A Match of Thrones by Terry R. R. Thomas published by Fantasy Tomes
in 2020 with 761 pages


