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.

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.

The objects will contain information about the properties and behavior. It is different from the class because the class only describes an object and the objects are created from the class.

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:

Name: Himanshu
Age : 22
Occupation : Professional Gamer

Python Object Initializationpython objects 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:

<__main__.Car object at 0x055965E0>

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 ‘int’>
<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:

[‘__abs__’, ‘__add__’, ‘__and__’, ‘__bool__’, ‘__ceil__’, ‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__divmod__’, ‘__doc__’, ‘__eq__’, ‘__float__’, ‘__floor__’, ‘__floordiv__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__index__’, ‘__init__’, ‘__init_subclass__’, ‘__int__’, ‘__invert__’, ‘__le__’, ‘__lshift__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__neg__’, ‘__new__’, ‘__or__’, ‘__pos__’, ‘__pow__’, ‘__radd__’, ‘__rand__’, ‘__rdivmod__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rfloordiv__’, ‘__rlshift__’, ‘__rmod__’, ‘__rmul__’, ‘__ror__’, ‘__round__’, ‘__rpow__’, ‘__rrshift__’, ‘__rshift__’, ‘__rsub__’, ‘__rtruediv__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__truediv__’, ‘__trunc__’, ‘__xor__’, ‘as_integer_ratio’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]

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:

Traceback (most recent call last):
  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:

TechVidvan

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:

<__main__.Student object at 0x055465E0>
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.