Python Class Tutorial – Python Object & Attributes Belonging to Class

Free Python courses with 57 real-time projects - Learn Python

In this Python Class tutorial, we are going to explore about Python Classes. how they work and access.

On the other hand, we will discuss what is the Python Object and different attributes belong to Python Class.

Atlast, we cover How can we delete an object, attributes, or a class in Python.

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, let’s start Python Class and Object Tutorial.

Python Class Tutorial - Python Object & Attributes Belonging to Class

Python Class Tutorial – Python Object & Attributes Belonging to Class

What is 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.

Let’s see the Python classes explained in detail.

Python Class Syntax

1. 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
            """

Output

Pass

As soon as we define a class, a Python 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

Output

<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")

>>> orange=fruit()

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 Python class.

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

>>> obj1=try1()
>>> obj1.mymethod()

Output

Hi

Hello

You can also create an attribute on the fly.

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

Output

‘Round’

2. Accessing Python Class Members

To access the members of a Python 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

Output

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

>>> orange.sayhi()

Output

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)

Output

I am size 7

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

>>> fruit.__doc__

Output

‘\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()

Output

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 Python class, but a method object for the instance object ‘orange’.

>>> fruit.salutation

Output

<function fruit.salutation at 0x0628FE40>
>>> orange.salutation

Output

<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()

Output

I am Orange and a size 7

What is the Python Object?

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

Output

‘Round’

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

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

Output

‘Orange’

We will check objects in detail in our next tutorial.

Attributes Belonging to Python Class

For explaining this, we’ll redefine the Python 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

Output

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

Output

‘Small’

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

Likewise, a Python 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()

Output

I am happy
>>> fruit.salutation

Output

<function fruit.salutation at 0x030C8390>

How to Delete Python Class, Attribute, and Object?

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

>>> del orange.shape
>>> orange.shape

Output

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

Output

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 Python class itself.

>>> fruit
<class '__main__.fruit'>
>>> del fruit
>>> fruit

Output

Traceback (most recent call last):File “<pyshell#133>”, line 1, in <module>

fruit

NameError: name ‘fruit’ is not defined

So, this was all about Python Class and Object Tutorial. Hope you like our explanation.

Python Interview Questions on Class

  1. What is class in Python? Explain with example
  2. How do you call a class in Python?
  3. Are Python classes slow?
  4. When should you use classes in Python?
  5. How do you define a class in Python?

Conclusion

In this Python Class tutorial, we opened ourselves to Python classes and how to Python create a 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.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

follow dataflair on YouTube

13 Responses

  1. Anish says:

    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 says:

      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.

  2. Radhika says:

    Hi
    I am following your blog only am very happy with your information. But coming to Classes and Objects I am unable to understand. When am trying to execute am getting some errors. So could you please help me how to overcome this problem.

    • DataFlair Team says:

      Hello Radhika,
      We would love to solve your query. Whatever errors you are experiencing, please ask us.

  3. Shiv says:

    How to debug Class’s methods as that require ‘self’. Could you share detail steps

  4. Pavan Josyula says:

    First of all, I wanted to say a big thanks to the blog developers because it has facilitated the learning of Python, R, Scala, and Data Science, etc. I am following this blog regularly, even I also joined this blog’s Telegram channels. My suggestion to this particular Python Class tutorial is you could make this tutorial more comprehensive. I read this tutorial thrice and understood the concepts, not in deeply, but to some extent, and I’ve got a question in this regard: “What is the difference between Python Class and Python Function?” “What makes the programmers prefer Class to Functions?”
    I’m grateful if you kindly answer the aforementioned queries.

    • DataFlair Team says:

      Thank you for commenting, it’s good to see a question like this. In programming, you have to think outside of what’s been given and question everything. Now coming back to your question, there are many different approaches to how you can plan to do your coding. Two popular approaches are procedural programming and object-oriented programming. In procedural programming, we use functions where we create functions for each specific task. On the other hand, in object-oriented programming (OOPs) we make classes and objects. There are a lot of benefits to using OOP. When building large applications it gets easier to maintain, scale the application or reuse the code we have written whereas procedural programming can get messy and hard to maintain at large scale. It is mainly used for small tasks. I hope this answers your question.

  5. Kishore Chowdhury says:

    In python, a class name starts with a block letter and functions contain underscore(_) symbol. Please update this. Otherwise its a really good tutorial.

  6. Basavaraj says:

    OMG! This is it. This is the best resource to learn python on the internet ever! You know what! This is better than phython official documents. Official docs stands nowhere near to this tutorial in terms of simplicity and clarity….keep it up guys. You are helping us who can’t afford heavy fees of fanciful online courses out there. Million salutes for your team. You are crazy! I mean…. it’s just mind-blowing…ok leave it…

    • DataFlair Team says:

      Thanks for such a wonderful compliment. It really means a lot to us. Stay with DataFlair to enhance your knowledge on different programming languages.

  7. Daniru says:

    Thanks For all your tutorials understood many of the concepts well !!!

  8. Mukesh says:

    Data flair super

Leave a Reply

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