How to Create a Simple Class in Python - Android Tricks 4 All
News Update
Loading...

Saturday, February 6, 2021

How to Create a Simple Class in Python

In an object oriented language, a class is an extensible piece of code that represents a template for creating and using the objects of that class. An object of a class simply refers to an instance of the defined class.

Python Class Basics

In the Python programming language, every piece of data is represented as an instance of some class. If you're not familiar with the language, see our beginner's guide to Python before moving on.

A class provides a set of behaviors in the form of member functions (also known as methods), which has implementations that are common to all instances of that class, and it also determines the way that the state information for its instance is represented in the form of attributes.

Read more: Class Methods in Python: The Important Differences

The code below represents an example of a defined class in Python. The class defined in the code provides an implementation of a RaceCar class.

Each instance of the class provides a simple model for different brands of cars and it contains the following state information: name of the car, name of the driver, license plate number of the car, current speed, speeding charge, and colour.

This car class, models a special sensor within each car that logs a fine of $50 against the driver of the car if he or she exceeds the legal speed limit of 140 miles per hour.

Example of a Class (Car Class)


class Car:
#Constructor
#the init method is responsible for initialising the values of the instance #variables in the class.
def __init__(self, car_name, driver_name, license_plate_number,
current_speed, speeding_charge, colour):
self.car_name = car_name
self._driver_name = driver_name
self._license_plate_number = license_plate_number
self._current_speed = current_speed
self._speeding_charge = speeding_charge
self._colour = colour
#Accessor methods
#The get_car_name method returns the name of the car
def get_car_name(self):
return self._car_name
#The get_driver_name method returns the name of the driver
def get_driver_name(self):
return self._driver_name
#The get_license_plate method returns the license plate of the car
def get_license_plate(self):
return self._license_plate
#The get_current_speed method returns the current speed at which the car is #moving
def get_current_speed(self):
return self._current_speed
#The get_speeding_charge method returns the total amount of money that the
#driver has to pay for over-speeding
def get_speeding_charge(self):
return self._speeding_charge
#The get_colour method returns the colour of our sweet ride!
def get_colour(self):
return self._colour
#Mutator methods
#The set_driver value changes the driver of our car.
def set_driver(self, new_driver):
self._driver_name = new_driver
#The speeding_ticket method ensures that the driver is charged 50 bucks when#he or she caught speeding above 140 miles per hour :(
def speeding_ticket(self, current_speed):
if current_speed <= 140:
return False
else:
self._speeding_charge += 50
return True
#The make_payment method ensures that the driver is able to pay for all the #amount that he or she owes for speeding ticket charges.
def make_payment(self, amount_paid):
self._speeding_charge -= amount_paid

An Explanation of the Python Class Example

The "Self" Parameter

Firstly, note that there is a difference between the method signature declared in the class and the method signature that is used by the programmer to call the function. For instance, the get_colour method as defined in the class takes one parameter which is the ‘self’ parameter.

However, when the programmer is calling this method on an instance of the class, he does not provide any parameters. This same phenomenon can be observed in the speeding_ticket method which is defined to take two parameters in the class (i.e. self and current_speed), but the programmer is able to execute this method by supplying the value for just the ‘current_speed’ parameter.

This is because the purpose of the ‘self’ parameter provided is to bind the method to the object instance upon which it was called and it is not a value to be given by the programmer.

The Constructor

A Constructor of a class refers to the method of the class that a user can call to create an object instance of that class. In the Car class, the user can create an object instance by using the following syntax:

#creating our very own Bugatti :)
Car(“Bugatti”, “David Sasu”, 90828, 0, 0, "Cherry Red")

The execution of this code results in a call to the __init__ method in the Car class. The responsibility of this method is to generate a newly created credit car object with the provided instance values. Each object of the Car class is constituted of six instance variables which are:

  • _car_name
  • _driver_name
  • _license_plate
  • _current_speed
  • _speeding_charge
  • _colour

Accessor Methods

These are methods which are written to access the state information of an object instance. In the Car class, the accessor methods which were written are:

  • get_car_name
  • get_driver_name
  • get_license_plate
  • get_current_speed
  • get_speeding_charge
  • get_colour

Mutator Methods:

These are methods which are written to alter the state information of an object instance. In the Car class, the mutator methods which were written are:

  • set_driver
  • speeding_ticket
  • make_payment

The Concept of Encapsulation

‘Encapsulation’ is a term that is used to describe a principle of object oriented design where components of a program should not reveal the internal details of their respective implementations. To increase your understanding of the concept of encapsulation, see our article on encapsulation.

Error Checking

Our implementation of the Car class is not robust since it is likely to crash or malfunction depending on the input that it receives from the programmer.

First, note that we do not check the types of the parameters of the speeding_ticket and the make_payment methods, nor do we check the types of any of the parameters of the constructor. This could lead to the program crashing if the user provides an argument that was not expected. For instance, if the user makes a call such as speeding_ticket(“chips ahoy”) the program would crash because the type that the method was expecting was an integer and not a string.

Now You Understand Python Class Basics

In this article, you have been introduced to the concept of a Python class and a Python class object. You have also been introduced to the ideas upon which a python class is built such as: encapsulation, the 'self' identifier, accessor methods and mutator methods.

With this information, you should be able to create a simple Python class on your own and test it :)



Comments


EmoticonEmoticon

Notification
This is just an example, you can fill it later with your own note.
Done