HomeProgrammingPythonPython Objects and Class

Python Objects and Class

Python is an object oriented programming language. Unlike procedure oriented programming, in which the main emphasis is on functions, object oriented programming stress on objects. Object is simply a collection of data (variables) and methods (functions) that act on those data.

Class is a blueprint for the object. We can think of class like a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. As, many houses can be made from a description, we can create many objects from a class. An object is also called an instance of a class and the process of creating this object is called instantiation.

Defining a Class in Python

Like function definitions begin with the keyword def, in Python, we define a class using the keywordclass. The first string is called docstring and has a brief description about the class. Although not mandatory, this is recommended. Here is a simple class definition.

class MyNewClass:
    '''This is a docstring. I have created a new class'''
    pass

A class creates a new local namespace where all its attributes are defines. Attributes may be data or functions. There are also special attributes in it that begins with double underscores (__). For example, __doc__ gives us the docstring of that class. As soon as we define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class.

>>> class MyClass:
...     "This is my second class"
...     a = 10
...     def func(self):
...         print('Hello')
...   
>>> MyClass.a
10

>>> MyClass.func
<function MyClass.func at 0x0000000003079BF8>

>>> MyClass.__doc__
'This is my second class'

Creating an Object in Python

We saw that the class object could be used to access different attributes. It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call.

>>> ob = MyClass()

This will create a new instance object named ob. We can access attributes of objects using the object name prefix. Attributes may be data or method. Method of an object are corresponding functions of that class. Any function object that is a class attribute defines a method for objects of that class. This means to say, since MyClass.func is a function object (attribute of class), ob.func will be a method object.

>>> ob = MyClass()
>>> MyClass.func
<function MyClass.func at 0x000000000335B0D0>
>>> ob.func
<bound method MyClass.func of <__main__.MyClass object at 0x000000000332DEF0>>

>>> ob.func()
Hello

You may have notices the self parameter in function definition inside the class. But we called the method simply as ob.func() without any arguments. It still worked. This is because, whenever an object calls its method, the object itself is pass as the first argument. So, ob.func() translates intoMyClass.func(ob). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument. For these reasons, the first argument of the function in class must be the object itself. This is conventionally called self. It can be named otherwise but we highly recommend to follow the convention.

Now you must be familiar with class object, instance object, function object, method object and their differences.

Constructors in Python

Class functions that begins with double underscore (__) are called special functions as they have special meaning. Of one particular interest is the __init__() function. This special function gets called whenever a new object of that class is instantiated. This type of function is also called constructors in Object Oriented Programming (OOP). We normally use it to initialize all the variables.

class ComplexNumber:
    def __init__(self,r = 0,i = 0):
        self.real = r
        self.imag = i

    def getData(self):
        print("{0}+{1}j".format(self.real,self.imag))

In the above example, we define a new class to represent complex numbers. It has two functions,__init__() to initialize the variables (defaults to zero) and getData() to display the number properly. Here, are some sample runs.

>>> c1 = ComplexNumber(2,3)
>>> c1.getData()
2+3j

>>> c2 = ComplexNumber(5)
>>> c2.attr = 10
>>> (c2.real, c2.imag, c2.attr)
(5, 0, 10)
>>> c1.attr
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'attr'

An interesting thing to note in the above step is that attributes of an object can be created on the fly. We created a new attribute attr for object c2 and we read it as well. But this did not create that attribute for object c1.

Deleting Attributes and Objects

Any attribute of an object can be deleted anytime, using the del statement.

>>> c1 = ComplexNumber(2,3)
>>> del c1.imag
>>> c1.getData()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag'

>>> del ComplexNumber.getData
>>> c1.getData()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'getData'

We can even delete the object itself, using the del statement.

>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined

Actually, it is more complicated than that. When we do c1 = ComplexNumber(1,3), a new instance object is created in memory and the name c1 binds with it. On the command del c1, this binding is removed and the name c1 is deleted from the corresponding namespace. The object however continues to exist in memory and if no other name is bound to it, it is later automatically destroyed. This automatic destruction of unreferenced objects in Python is also called garbage collection.

Deleting Object in Python

- A word from our sponsors -

spot_img

Most Popular

Leave a reply

Please enter your comment!
Please enter your name here

More from Author

500 million WhatsApp Numbers have been Hacked from 84 nations

A shocking allegation claims that the phone numbers of nearly 500...

Freddy Film Review

Kartik Aryan alias Freddy Ginwala is a successful dentist. When it...

Putin Plans to Replace SWIFT With Blockchain Payment System

Russian President Vladimir Putin criticized monopolies in global financial payment systems...

Bitget Crypto Exchange Flips Layoff Trend, Expands to Africa

The cryptocurrency winter has been colder for some than others. While...

- A word from our sponsors -

spot_img

Read Now

500 million WhatsApp Numbers have been Hacked from 84 nations

A shocking allegation claims that the phone numbers of nearly 500 million WhatsApp users have been hacked and listed for sale online. The issue around a data breach has already included Meta or one of its services. 487 million WhatsApp users' phone numbers have reportedly been compromised and are...

Freddy Film Review

Kartik Aryan alias Freddy Ginwala is a successful dentist. When it comes to his personal life, he is not successful as since last 5 years he is desperately looking for his soulmate. One day he gets his love but that love changes his life completely. Analysis of the...

Putin Plans to Replace SWIFT With Blockchain Payment System

Russian President Vladimir Putin criticized monopolies in global financial payment systems and called for an independent and blockchain-based settlement network, speaking at the International AI Travel conference in Moscow on 24 November. Russia’s Rostec Group, a government organization, has developed a blockchain platform to launch a digital system for...

Bitget Crypto Exchange Flips Layoff Trend, Expands to Africa

The cryptocurrency winter has been colder for some than others. While some cryptocurrency exchanges are forced to conduct massive employee layoffs to weather the bear market, others like Bitget Crypto Exchange continue to make massive hires to improve their services, Bitget crypto exchange flips the layoff trend. On...

New iPhone15 Leaks Reveals Stunning Design and No Sim Card

The first iPhone 15 leaks have already promised a combination of eye-catching and controversial design changes. And excitement is only likely to grow further now a new exclusive has revealed another stunning design decision. In a move that would see Apple step back in time, a new leak from anonymous...

Get iPhone 14 Under 60000 on Flipkart – Limited Time

The original price of the iPhone 14 is Rs 79,900. However, you can get the device at a discount of Rs 5000 if you have an HDFC bank card how the deal works The original price of the iPhone 14 is Rs 79,900. However, you can get the device...

Download Unofficial TWRP for Samsung A135 Exynos

​ DISCLAIMER: I WAS NEVER, HAVE NEVER BEEN, AND WILL NEVER BE RESPONSIBLE FOR ANY DAMAGES AGAINST YOUR DEVICES. We are not responsible for bricked devices, dead SD cards, thermonuclear war, or you getting fired because the alarm app failed. Please do some research if you have any concerns about the...

Android 13 and One UI 5 for Samsung Galaxy A52

Samsung was widely panned for its slow and non-existent software support during the TouchWiz era. Over the years, though, it has made considerable improvements in this area, and with One UI 5, the Korean giant has raised the bar to a new level altogether. The Galaxy S22 was...

Presearch Coin | Earn Crypto While You Search | 25 Pre Coin for Signup

Presearch offers PRE tokens as a reward for those who search through the platform. These tokens have intrinsic value because they are the access tokens purchased by advertisers to target searchers entering certain keywords. The amount currently provided to searchers is 0.25 PRE if they search through the...

Nodle Joins First Polkadot Parachain Auction

Nodle, one of the world’s largest ecosystems of connected devices, today announced their entrance into Polkadot’s inaugural parachain slot auction and crowdloan. Nodle provides infrastructure, software, and data access to the Internet of Things (IoTs) using Bluetooth Low Energy (BLE) on existing smartphones. Polkadot is a blockchain...

How to Mine Nodle Cash IoT Network

Introduction Nodle – built on a Bluetooth Low Energy (BLE) network – is a connectivity provider for the Internet of Things (IoT). The network helps companies and cities collect data from their devices, sensors, and tags. The Nodle Network can help manufactures/operators of electronic devices collect valuable data and also help...

Ethereum Whales on Move – Relocate Over $500,000,000 Matter of Hours

A massive amount of Ethereum (ETH) worth half a billion dollars is on the move, as crypto whales relocate their ETH troves. This Friday, blockchain tracker Whale Alert spotted a series of transactions in which large Ethereum holders moved 237,419 ETH, worth $557,777,068, in just over 10 hours. In...