Site icon DataFlair

Python Class Tutorial – Python Object & Attributes Belonging to Class

Python Class Tutorial - Python Object & Attributes Belonging to Class

Python Class Tutorial - Python Object & Attributes Belonging to Class

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

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.

Exit mobile version