[go: up one dir, main page]

0% found this document useful (0 votes)
13 views13 pages

PY0101EN 3 4 Classes

Python classes

Uploaded by

kabhikabirsingh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views13 pages

PY0101EN 3 4 Classes

Python classes

Uploaded by

kabhikabirsingh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Classes and Objects in Python

Estimated time needed: 40 minutes

Objectives
After completing this lab you will be able to:

Work with classes and objects


Identify and define attributes and methods

Table of Contents

Introduction to Classes and Objects


Creating a class
Instances of a Class: Objects and Attributes
Methods
Creating a class
Creating an instance of a class Circle
The Rectangle Class

Introduction to Classes and Objects

Creating a Class
The first step in creating a class is giving it a name. In this notebook, we will
create two classes: Circle and Rectangle. We need to determine all the data that
make up that class, which we call attributes. Think about this step as creating a
blue print that we will use to create objects. In figure 1 we see two classes, Circle
and Rectangle. Each has their attributes, which are variables. The class Circle
has the attribute radius and color, while the Rectangle class has the attribute
height and width. Let’s use the visual examples of these shapes before we get to
the code, as this will help you get accustomed to the vocabulary.

Figure 1: Classes circle and rectangle, and each has their own attributes. The
class Circle has the attribute radius and colour, the class Rectangle has the
attributes height and width.

Instances of a Class: Objects and Attributes


An instance of an object is the realisation of a class, and in Figure 2 we see three
instances of the class circle. We give each object a name: red circle, yellow
circle, and green circle. Each object has different attributes, so let's focus on the
color attribute for each object.

Figure 2: Three instances of the class Circle, or three objects of type Circle.

The colour attribute for the red Circle is the colour red, for the green Circle object
the colour attribute is green, and for the yellow Circle the colour attribute is
yellow.

Methods
Methods give you a way to change or interact with the object; they are functions
that interact with objects. For example, let’s say we would like to increase the
radius of a circle by a specified amount. We can create a method called
add_radius(r) that increases the radius by r. This is shown in figure 3, where
after applying the method to the "orange circle object", the radius of the object
increases accordingly. The “dot” notation means to apply the method to the
object, which is essentially applying a function to the information in the object.

Figure 3: Applying the method “add_radius” to the object orange circle object.

Creating a Class
Now we are going to create a class Circle, but first, we are going to import a
library to draw the objects:

In [8]: # Import the library

import matplotlib.pyplot as plt


%matplotlib inline

The first step in creating your own class is to use the class keyword, then the
name of the class as shown in Figure 4. In this course the class parent will always
be object:
Figure 4: Creating a class Circle.

The next step is a special method called a constructor __init__ , which is used
to initialize the object. The inputs are data attributes. The term self contains
all the attributes in the set. For example the self.color gives the value of the
attribute color and self.radius will give you the radius of the object. We also
have the method add_radius() with the parameter r , the method adds the
value of r to the attribute radius. To access the radius we use the syntax
self.radius . The labeled syntax is summarized in Figure 5:

Figure 5: Labeled syntax of the object circle.

The actual object is shown below. We include the method drawCircle to


display the image of a circle. We set the default radius to 3 and the default
colour to blue:

In [1]: # Create a class Circle

class Circle(object):

# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color

# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)

# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.c
plt.axis('scaled')
plt.show()

Creating an instance of a class Circle


Let’s create the object RedCircle of type Circle to do the following:

In [2]: # Create an object RedCircle

RedCircle = Circle(10, 'red')

We can use the dir command to get a list of the object's methods. Many of
them are default Python methods.

In [3]: # Find out the methods can be used on the object RedCircle

dir(RedCircle)
Out[3]: ['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'add_radius',
'color',
'drawCircle',
'radius']

We can look at the data attributes of the object:

In [4]: # Print the object attribute radius

RedCircle.radius

Out[4]: 10

In [5]: # Print the object attribute color

RedCircle.color

Out[5]: 'red'

We can change the object's data attributes:

In [6]: # Set the object attribute radius

RedCircle.radius = 1
RedCircle.radius

Out[6]: 1
We can draw the object by using the method drawCircle() :

In [9]: # Call the method drawCircle

RedCircle.drawCircle()

We can increase the radius of the circle by applying the method add_radius() .
Let's increases the radius by 2 and then by 5:

In [10]: # Use method to change the object attribute radius

print('Radius of object:',RedCircle.radius)
RedCircle.add_radius(2)
print('Radius of object of after applying the method add_radius(2):',RedCirc
RedCircle.add_radius(5)
print('Radius of object of after applying the method add_radius(5):',RedCirc

Radius of object: 1
Radius of object of after applying the method add_radius(2): 3
Radius of object of after applying the method add_radius(5): 8

Let’s create a blue circle. As the default colour is blue, all we have to do is
specify what the radius is:

In [11]: # Create a blue circle with a given radius

BlueCircle = Circle(radius=100)
As before, we can access the attributes of the instance of the class by using the
dot notation:

In [12]: # Print the object attribute radius

BlueCircle.radius

Out[12]: 100

In [13]: # Print the object attribute color

BlueCircle.color

Out[13]: 'blue'

We can draw the object by using the method drawCircle() :

In [14]: # Call the method drawCircle

BlueCircle.drawCircle()

Compare the x and y axis of the figure to the figure for RedCircle ; they are
different.
The Rectangle Class
Let's create a class rectangle with the attributes of height, width, and color. We
will only add the method to draw the rectangle object:

In [15]: # Create a new Rectangle class for creating a rectangle object

class Rectangle(object):

# Constructor
def __init__(self, width=2, height=3, color='r'):
self.height = height
self.width = width
self.color = color

# Method
def drawRectangle(self):
plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height ,f
plt.axis('scaled')
plt.show()

Let’s create the object SkinnyBlueRectangle of type Rectangle. Its width will
be 2 and height will be 3, and the color will be blue:

In [16]: # Create a new object rectangle

SkinnyBlueRectangle = Rectangle(2, 3, 'blue')

As before we can access the attributes of the instance of the class by using the
dot notation:

In [17]: # Print the object attribute height

SkinnyBlueRectangle.height

Out[17]: 3

In [18]: # Print the object attribute width

SkinnyBlueRectangle.width

Out[18]: 2

In [19]: # Print the object attribute color

SkinnyBlueRectangle.color

Out[19]: 'blue'

We can draw the object:


In [20]: # Use the drawRectangle method to draw the shape

SkinnyBlueRectangle.drawRectangle()

Let’s create the object FatYellowRectangle of type Rectangle:

In [ ]: # Create a new object rectangle

FatYellowRectangle = Rectangle(20, 5, 'yellow')

We can access the attributes of the instance of the class by using the dot
notation:

In [ ]: # Print the object attribute height

FatYellowRectangle.height

In [ ]: # Print the object attribute width

FatYellowRectangle.width

In [ ]: # Print the object attribute color

FatYellowRectangle.color

We can draw the object:


In [ ]: # Use the drawRectangle method to draw the shape

FatYellowRectangle.drawRectangle()

Scenario: Car dealership's inventory


management system
You are working on a Python program to simulate a car dealership's inventory
management system. The system aims to model cars and their attributes
accurately.

Task-1. You are tasked with creating a Python program


to represent vehicles using a class. Each car should
have attributes for maximum speed and mileage.
In [ ]: #Type your code here

Click here for the solution

Task-2. Update the class with the default color for all
vehicles," white".
In [ ]: #Type your code here

Click here for the solution

Task-3. Additionally, you need to create methods in the


Vehicle class to assign seating capacity to a vehicle.

In [ ]: #Type your code here

Click here for the solution

Task-4. Create a method to display all the properties of


an object of the class.
In [ ]: #Type your code here

Click here for the solution


Task-5. Additionally, you need to create two objects of
the Vehicle class object that should have a max speed
of 200kph and mileage of 50000kmpl with five seating
capacities, and another car object should have a max
speed of 180kph and 75000kmpl with four seating
capacities.
In [ ]: #Type your code here

Click here for the solution

The last exercise!


Congratulations, you have completed your first lesson and hands-on lab in
Python.

Author
Joseph Santarcangelo

Other contributors
Mavis Zhou

Change Log
Date (YYYY-MM-
Version Changed By Change Description
DD)

Akansha
2023-05-16 2.2 updated lab under maintenance
Yadav

2022-01-10 2.1 Malika Removed the readme for GitShare

Moved lab to course repo in


2020-08-26 2.0 Lavanya
GitLab

© IBM Corporation 2020. All rights reserved.

This notebook was converted to PDF with convert.ploomber.io

You might also like