Python Class Tutorial and Object Oriented Programming 2


1. Python Class Tutorial

Like we’ve often said, Python is an object-oriented language. This means it focuses on objects instead of procedures. An object can model the real world. So now, in our series of Python tutorials, we move forward to object-oriented programming and learn the concepts of Python class and Python class examples.

Python Class Tutorial

Python Class Tutorial

2. Introduction to Python Class

A class is a blueprint for objects- one class for any number of objects of that type. You can also call it an abstract data type. Interestingly, it contains no values itself, but it is like a prototype for objects. Lets see the Python classes explained in detail.

3. Syntax of Class in Python

a. Defining a Python Class

To define a class in python programming, we use the ‘class’ keyword. This is like we use ‘def’ to define a function in python. And like a function, a Python3 class may have a docstring as well. We can do this to write a couple of lines explaining what the class does. To focus on the syntax here, we will pass in a ‘pass’ statement in its body for now.

>>> class fruit:
"""
This Python3 class creates instances of fruits
"""

Pass

As soon as we define a class, a Python programming class object is created. But remember, you can only name a class according to the identifier naming rules as we discussed in our tutorial on Python Variables.

>>> fruit

<class ‘__main__.fruit’> #The class object

A Python3 class may have attributes and methods to execute on that data. We declare/define these the usual way. Let’s take an example.

>>> class fruit:
"""
This class creates instances of fruits
"""
color=''
def sayhi(self):
print("Hi")

Here, color is an attribute, and sayhi() is a method to call on an object of class fruit.

You can also define a regular first-class function inside a method, but not outside it in a class.

>>> class try1:
def mymethod(self):
def sayhello():
print("Hello")
print("Hi")
sayhello()
>>> obj1=try1()
>>> obj1.mymethod()

Hi

Hello

You can also create an attribute on the fly.

>>> orange.shape='Round'
>>> orange.shape

‘Round’

b. Accessing Python Class Members

To access the members of a class, we use the dot operator. Let’s create an orange object for our fruit class.

>>> orange=fruit()

Now, let’s access the color attribute for orange.

>>> orange.color

This returns an empty string because that is what we specified in the class definition.

>>> orange.sayhi()

Hi

Here, we called the method sayhi() on orange. A method may take arguments, if defined that way.

>>> class fruit:
def size(self,x):
print(f"I am size {x}")
>>> orange=fruit()
>>> orange.size(7)

I am size 7

A class may also have some special attributes, like __doc__ for the docstring.

>>> fruit.__doc__

‘\n\tThis class creates instances of fruits\n\t’

To get more insight into methods in Python, read up on Python Methods. But for now, we’ll take an example including the __init__() magic method and the self parameter.

>>> class fruit:
def __init__(self,color,size):
self.color=color
self.size=size
def salutation(self):
print(f"I am {self.color} and a size {self.size}")
>>> orange=fruit('Orange',7)
>>> orange.salutation()

I am Orange and a size 7

As you can see, the __init__() method is equivalent to a constructor in C++ or Java. It gets called every time we create an object of the class. Likewise, the self parameter is to tell the interpreter to deal with the current object. This is like the ‘this’ keyword in Java. But you don’t have to call it ‘self’; you can call it anything. The object is passed as the first argument, fitting in for ‘self’. Here, orange.salutation() translates to fruit.salutation(orange).

Also, salutation is a function object for the class, but a method object for the instance object ‘orange’.

>>> fruit.salutation
<function fruit.salutation at 0x0628FE40>
>>> orange.salutation
<bound method fruit.salutation of <__main__.fruit object at 0x062835F0>>

You can store a method object into a variable for later use.

>>> sayhi=orange.salutation
>>> sayhi()

I am Orange and a size 7

4. Introduction to Python Objects

Now, how useful is a Python3 class without an object? If a class is an idea, an object is its execution.

When we create an object, its __init__() method is called. And like we previously discussed, the object gets passed to the class through the function with the ‘self’ keyword.

>>> orange=fruit('Orange',7)

Here, we passed ‘Orange’ and 7 as values for the attributes color and size. We can also declare attributes for an object on the fly. See how.

>>> orange.shape='Round'
>>> orange.shape

‘Round’

You can assign the values of an object in python to another.

>>> apple=orange
>>> apple.color

‘Orange’

We will check objects in detail in our next tutorial.

5. Attributes Belonging to Python Class

For explaining this, we’ll redefine the class fruit.

>>> class fruit:
size='Small'
def __init__(self,color,shape):
self.color=color
self.shape=shape
def salutation(self):
print(f"I am {self.color} and a shape {self.shape}")

Here, the attribute ‘size’ belongs to the class, but we can call it on an object as well.

>>> fruit.size

‘Small’

>>> orange=fruit('Orange','Round')
>>> orange.size

‘Small’

Since we redefined the class, we declared the object again as well.

Likewise, a class can contain a function as well.

>>> class fruit:
size='Small'
def __init__(self,color,shape):
self.color=color
self.shape=shape
def salutation():
print(f"I am happy")
>>> fruit.salutation()

I am happy

>>> fruit.salutation
<function fruit.salutation at 0x030C8390>

6. Deleting in Python Class

You can delete an attribute, an object, or a class using the del keyword.

>>> del orange.shape
>>> orange.shape
Traceback (most recent call last):
File "<pyshell#118>", line 1, in <module>
orange.shape

AttributeError: ‘fruit’ object has no attribute ‘shape’

Let’s try deleting an object.

>>> del orange
>>> orange
Traceback (most recent call last):
File "<pyshell#120>", line 1, in <module>
orange

NameError: name ‘orange’ is not defined

Finally, let’s try deleting the class itself.

>>> fruit
<class '__main__.fruit'>
>>> del fruit
>>> fruit
Traceback (most recent call last):
File "<pyshell#133>", line 1, in <module>
fruit

NameError: name ‘fruit’ is not defined

7. Conclusion

In this tutorial, we opened ourselves to Python classes and how to Python create class. We saw how to declare and access attributes and methods in python. A little too much to take on at once? Get practicing. Next, we’ll talk about objects in python.


Leave a comment

Your email address will not be published. Required fields are marked *

2 thoughts on “Python Class Tutorial and Object Oriented Programming

  • Anish

    The website is excellent. I have been following it since 2weeks. I understood every concept clearly except CLASSES AND OBJECTS .I don’t know why I’m facing problem in learning these topics I have read for 2 to 3 times but still I’m not getting it. Please I kindly request you to suggest any strategy .

    • Data Flair

      Hi Anish,
      Thanks for Following us!!

      If you have gone over the same article “Python Class & Object” almost thrice, then we suggest you should try practicing along in the IDLE as you find the examples in our blog.
      Do it one example at a time. Look at the code and the output, try to figure out how.
      Maybe this is about the self-keyword? Well, that is to declare it to Python to refer to the current object.

      Python is a wonderful language and Python classes and objects are just a bridge it observes to the object-oriented side of it.
      This is simple and you should be able to make it with enough practice. Do not lose hope!
      We hope you can conquer this hurdle you’ve stumbled across and serve as motivation to others to pursue programming with Python.

      Hope, this will solve your query, please leave your feedback.