Python Class Tutorial – Python Object & Attributes Belonging to Class
Master Python with 70+ Hands-on Projects and Get Job-ready - 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.
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
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
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
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
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
A Python class may also have some special attributes, like __doc__ for the docstring.
>>> fruit.__doc__
Output
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
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
>>> orange.salutation
Output
You can store a method object into a variable for later use.
>>> sayhi=orange.salutation >>> sayhi()
Output
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
You can assign the values of an object in python to another.
>>> apple=orange >>> apple.color
Output
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
>>> orange=fruit('Orange','Round') >>> orange.size
Output
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
>>> fruit.salutation
Output
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
- What is class in Python? Explain with example
- How do you call a class in Python?
- Are Python classes slow?
- When should you use classes in Python?
- 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 you like this article? If Yes, please give DataFlair 5 Stars on Google
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 .
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.
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.
Hello Radhika,
We would love to solve your query. Whatever errors you are experiencing, please ask us.
How to debug Class’s methods as that require ‘self’. Could you share detail steps
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.
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.
In python, a class name starts with a block letter and functions contain underscore(_) symbol. Please update this. Otherwise its a really good tutorial.
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…
Thanks for such a wonderful compliment. It really means a lot to us. Stay with DataFlair to enhance your knowledge on different programming languages.
Thanks For all your tutorials understood many of the concepts well !!!
Data flair super
Thank you mukesh, if you really liked it don’t forget to rate us on google.