Python Class and Object
In this tutorial you will learn:
- Classes and Objects
- Class in Python
- Object in Python
- Alter an Object
Classes and Objects
Object Oriented Programming Languages works with two main features Class and Object. In this programming paradigm we create containers that contains different properties and methods. These methods are used to modify the properties in some way and we name these containers as Classes. Objects are instances of a Class and they have access to the properties and methods of that class.
Class in Python
Python is also an Object Oriented Programming Language. We can create different containers with the keyword “class” and add properties and methods to it.
Example:
Creating a class in Python is simple. We use “class” keyword followed by the name of the class and then we write its properties and methods below.
- class Vehicle:
- car = "Tesla"
- truck = "Cyber Truck"
- bike = "Cyber Bike"
In Object Oriented Languages whenever we create a class a function is called to initialize the class and that function is known as a constructor. We can initialize the class with some default values. In python constructor is defined by the keyword “init”. Let’s use that function in our vehicle example.
- class Vehicle:
- def __init__(self, model,vehicleType, color):
- self.model = model
- self.vehicleType = vehicleType
- self.color = color
Object in Python
As already mentioned objects are instances of a Class and they have access to those properties and methods. In order to create objects in Python we can have a look at the example below.
Example:
- class Vehicle:
- def __init__(self, model, vehicleType, color):
- self.model = model
- self.vehicleType = vehicleType
- self.color = color
- myVehicle = Vehicle(2020,"Truck", "Red")
- print("** Vehicle Details **")
- print("Model", myVehicle.model)
- print("Vehicle Type", myVehicle.vehicleType)
- print("Color", myVehicle.color)
- print("\n\nRewriting Vehicle class with __init__ constructor")
- class Vehicle:
- def __init__(self, model,vehicleType, color):
- self.model = model
- self.vehicleType = vehicleType
- self.color = color
- def vehicleDetails(self):
- print("\n\n-- Vehicle Details using behicle details function --")
- print("Model", self.model)
- print("Vehicle Type", self.vehicleType)
- print("Color", self.color)
- mySecondVehicle = Vehicle(2010, "Car", "Blue")
- mySecondVehicle.vehicleDetails()
Alter an Object
We can alter an object in different ways. We can delete an object and set values to its properties. Deleting an Object is very simple. We just need to use the del keyword followed by the variable name.
del myVehicle
In order to alter the properties we can simply do that by using by calling the class property with the object and assign the updated value
myVehicle.color = “Green”
Add new comment
- 357 views