Python Objects – Learn OOPs concept with syntax and examples
As we know that Python is an object-oriented programming language, the main focus in object-oriented programming are classes and objects. These are the two main concepts of all the Object-oriented programming languages.
In this article, we will learn about class then see how to create Python objects and see some of the operations on it. So let’s get started with a quick look at the class.
What is a Class in Python?
A class is like a blueprint that defines the properties and behavior of an object.
As an example, a Cat class can have several properties like name, size, weight, color, age, health, etc. and it will have certain behaviors like walk, jump, scratch, eat, etc.
The class is a model that will define the structure of class properties and it’s behaviors. When you create an object from a class, you instantiate it, meaning you create a specific instance of the class with its own unique set of data. Classes also support inheritance, allowing you to create new classes based on existing ones, promoting code reuse and modularity.
Python Example of a class:
Code:
class Person: def __init__(self, name, age, occupation): self.name = name self.age = age self.occupation = occupation def details(self): print(“Name:”, self.name) print(“Age :”, self.age) print(“Occupation :”, self.occupation)
What is an Object in Python?
An object is a representation of a real-world object. It can be anything like a cat, dog, car, student, employee, chair, mobile, device, etc.
Objects contain information about their properties and behaviors, making them concrete instances of their respective classes. While a class provides a blueprint for creating objects, an object is an actual instance that holds real data. For instance, you might have a class called Car with properties like color, model, and speed, and behaviors like accelerate and brake. When you create an object from this class, you get a specific car with its own unique attributes and abilities.
This is one way to create an object of a class.
Code:
p1 = Person(“Himanshu”, 22, “Professional Gamer”)
Here, p1 is an object of class Person. That has 3 properties: name, age, and occupation and a method(behavior). Now we can use the object to perform actions or see it’s behavior.
Code:
p1.details()
Output:
Age : 22
Occupation : Professional Gamer
Python Object Initialization
During the creation or initialization of objects, Python calls the __init__() method which is called as a constructor that we use to initialize attributes of a class.
How to initialize an object of a class depends on how the class is defined.
There are two ways to initialize or create objects.
- With arguments (for classes that have arguments in the constructor)
- Without arguments (for classes that don’t have any argument in the constructor)
1. With Arguments
We have already seen an example of this in our previous example of Person class. During the creation of the class, we passed 3 arguments: name, age, and occupation.
So to create the object of Person class we have to provide these 3 arguments in the brackets.
Code:
obj = Person(“John”, 45, “Teacher”)
2. Without Arguments
In the definition of the class, if the constructor is not defined or there are no arguments in the constructor other than self, then the objects of this class will be created without any arguments.
First, let’s create a class.
Code:
class Car: model='' def display(self): print("The Model of the Car is :",self.model) def setModel(self, model): self.model = model
Here, we have not created the __init__() method but Python automatically creates it without any arguments.
So, we can now create the object of the Car class.
Code:
car1 = Car() print(car1)
Output:
Everything in Python is an Object
This is an important concept of Python that everyone should be aware of.
In Python, everything is an object. To prove this to you, first, we will see some examples: We will see the type of various data types like numbers, strings, etc.
Code:
print(type(10)) print(type("Hey")) print(type({1,2,3})) print(type(True)) def greet(): print("Welcome") class Emp: pass print(type(greet)) print(Emp)
Output:
<class ‘str’>
<class ‘set’>
<class ‘bool’>
<class ‘function’>
<class ‘__main__.Emp’>
As you can see, Strings, numbers, Booleans, functions, and classes are all objects. They all derive from the base class ‘object’.
An integer is not just a value, it is an object that has several properties and methods. To see them we can use the dir() function.
Code:
dir(4)
Output:
Dynamically Adding Properties to a Class
Python is a flexible language, we can add properties to an object even after declaring the object.
Let’s see this with an example.
Code:
class Person: pass p = Person() print(p.name)
Output:
File “C:\Users\Techvidvan\AppData\Local\Programs\Python\Python38-32\test.py”, line 6, in <module>
print(p.name)
AttributeError: ‘Person’ object has no attribute ‘name’
The class definition is empty and there is no name attribute, now let’s add the name attribute by simply assigning it a value.
Code:
p.name = 'TechVidvan' print(p.name)
Output:
Delete an Object in Python
Sometimes we need to explicitly delete an object.
Although Python garbage collection is automatic, which means that the user does not need to worry about allocating memory or freeing up space by deallocating.
With the del keyword we can explicitly control the scope of the variable by deleting from the local or a global variable.
Code:
class Student: def getInfo(self): print("I'm a student at DGM") alan = Student() print(alan) del alan print(alan)
Output:
Traceback (most recent call last):
File “C:\Users\Techvidvan\AppData\Local\Programs\Python\Python38-32\test.py”, line 9, in <module>
print(alan)
NameError: name ‘alan’ is not defined
Here, we created an object alan and later deleted it using the del keyword then if we try to access the object we get a NameError.
Summary
In this article, we discussed the Python objects but before that, we saw a quick look at Python class. Later on, we understood how to initialize or create objects in Python, we also talked on how everything in Python is objects. In the end, we saw how to add properties to an object and also delete it.
I hope you are also practicing the concepts on your system.