Python Classes and Objects - NullClass

Special Sale the courses from 497 rs for limited time.

Python Classes and Objects

Python Classes and Objects

 

eLearning: PY4E Python for Beginners | basics of programming

 

  • In this blog, you will be learning about the core functionality of Python classes and objects. You will learn what is meant by a class, how would you proceed with creating a class and also how would you be able to use it in your program.

Python Classes and Objects

 

Python Objects and Classes (Class, Object, function __int()__)

 

  1. Python is an object-oriented programming language. Unlike the procedure-oriented programming, wherein the main emphasis is given to the functions, object-oriented programming stress mainly on the objects.
  2. An object is just a collection of data (variables) and methods (functions) that perform some action on those data. Likewise, a class is simply a blueprint for that very object.
  3. You can think of a class as a sketch or a prototype of a house. It contains all the details about the floors, doors, windows, and the basic floor plan etc. Based on these illustrations and descriptions we build a house. Here house is the object.
  4. As many houses can be made from the blueprint of a house, similarly we can create many objects from using a class. An object can also be called an example of a class and the process used for creating this object is called instantiation.

Defining a Class in Python programming language

 

A Comprehensive Guide for Classes in Python | by Soner Yıldırım | Towards Data Science

 

  • Just like function definitions begin with the def keyword in Python, the definition of class also begins with the class keyword.
  • The first string inside of the class is known as docstring and has a very brief description of the class inside it. Although it is not mandatory yet, this is highly recommended.

Here is a very simple class definition.

class MyNewClass:

”’This is a docstring. I have created a new class”’

pass

In a class a new local known as namespace is created wherein all of its attributes are defined. Attributes might be data or functions.

There are also some special attributes in it that begin with double underscores. For instance, __doc__ gives us the docstring of that specific class.

As soon as we are done with defining a class, another new class object gets created with the very same name. This class object enables us to access the different attributes as well as to instantiate the new objects of that particular class.

class Person:

“This is a person class”

age = 10

 

def greet(self):

print(‘Hello’)

 

 

# Output: 10

print(Person.age)

 

# Output: <function Person.greet>

print(Person.greet)

 

# Output: “This is a person class”

print(Person.__doc__)

Output

10

<function Person.greet at 0x7fc78c6e8160>

This is a person class

Creation of an Object in Python

 

Creating Objects in Python

 

As we saw that the class object might be used to access the different attributes.

We can also use it to create new object instances (instantiation) of that class. This procedure which is done to create an object is very similar to a function call.

>>> harry = Person()

This will help us create a new object instance named harry. This can be accessed through the attributes of objects using the prefix of the object name.

Attributes may be data or even method. Methods of an object correspond to the functions of that particular class.

The meaning of this statement is that, since Person.greet is a function object (attribute of class), Person.greet will also be a method object.

class Person:

“This is a person class”

age = 10

 

def greet(self):

print(‘Hello’)

 

 

# create a new object of Person class

harry = Person()

 

# Output: <function Person.greet>

print(Person.greet)

 

# Output: <bound method Person.greet of <__main__.Person object>>

print(harry.greet)

 

# Calling object’s greet() method

# Output: Hello

harry.greet()

Output

<function Person.greet at 0x7fd288e4e160>

<bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>>

Hello

  • You might have noticed the self parameter in the function definition inside the class but we have called the method simply as harry.greet() without the use of any arguments. It will still have worked.
  • This is due to the fact that whenever an object calls its method, the object itself is passed as the very first argument. So, harry.greet() translates into Person.greet(harry).
  • Generally speaking, calling a method with a list of n arguments is almost equivalent to calling the corresponding function along with an argument list that is created by inserting the method’s object just before the very first argument.
  • For these very reasons, the first argument of the function in a class must be the object itself. Conventionally this is called as self. It can also be named otherwise but we highly recommend you to follow the convention.

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

Constructors in Python

Class functions that start with double underscore __ are known as special functions as they have some special meaning.

Of one particular interest is the __init__() function. This is a special function which gets called whenever a new object of that class is created.

This type of a function is also called constructors in Object Oriented Programming (OOP). We usually use it to initialize all of the variables.

class ComplexNumber:

def __init__(self, r=0, i=0):

self.real = r

self.imag = i

 

def get_data(self):

print(f'{self.real}+{self.imag}j’)

 

 

# Create a new ComplexNumber object

num1 = ComplexNumber(2, 3)

 

# Call get_data() method

# Output: 2+3j

num1.get_data()

 

# Create another ComplexNumber object

# and create a new attribute ‘attr’

num2 = ComplexNumber(5)

num2.attr = 10

 

# Output: (5, 0, 10)

print((num2.real, num2.imag, num2.attr))

 

# but c1 object doesn’t have attribute ‘attr’

# AttributeError: ‘ComplexNumber’ object has no attribute ‘attr’

print(num1.attr)

Output

2+3j

(5, 0, 10)

Traceback (most recent call last):

File “<string>”, line 27, in <module>

print(num1.attr)

AttributeError: ‘ComplexNumber’ object has no attribute ‘attr’

In the above instance, we have defined a new class to represent the complex numbers. It includes two functions, __init__() to initialize the given variables (defaults to zero) and get_data() to display the given numbers properly.

An amusing thing to note in the above step is that the attributes of an object can also be created on the fly. We have created a new attribute attr for object num2 and read it as well. But doing this does not create that attribute for object num1.

Deleting the Attributes and Objects

You can delete any attribute of an object anytime, using the del statement. Try the following on the Python shell to see the output of the code.

>>> num1 = ComplexNumber(2,3)

>>> del num1.imag

>>> num1.get_data()

Traceback (most recent call last):

AttributeError: ‘ComplexNumber’ object has no attribute ‘imag’

 

>>> del ComplexNumber.get_data

>>> num1.get_data()

Traceback (most recent call last):

AttributeError: ‘ComplexNumber’ object has no attribute ‘get_data’

Using the del statement given code we can even delete the object itself.

>>> c1 = ComplexNumber(1,3)

>>> del c1

>>> c1

Traceback (most recent call last):

NameError: name ‘c1’ is not defined

 

  • It is more complicated than that. When we do c1 = ComplexNumber(1,3), a new example object is created in the memory and the name c1 binds with it.
  • On the command del c1, the binding is removed and the name c1 is deleted from the namespace. The object however continues to still exist in the memory and if no other name has been bound to it, it is later automatically annihilated.
  • This type of automatic destruction of the unreferenced objects in Python is also called as garbage collection.
  • Deleting objects in Python removes the name binding

 

Thank you for reading this blog folks! I hope you have a wonderful rest of your day!!

For more Information like this do visit our page NullClass !

October 9, 2021

0 responses on "Python Classes and Objects"

Leave a Message