Python Class Tutorial – Python Object & Attributes Belonging to Class

1. Python Class Tutorial

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

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.

Let’s see the Python classes explained in detail.

3. Python Class Syntax

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

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 argments, 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 Python 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 Python 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. 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

‘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 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

‘Small’

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

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

I am happy

>>> fruit.salutation

<function fruit.salutation at 0x030C8390>

Python Interview Questions

6. 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

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

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

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

Reference

4 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.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.