Python Classes – Learn Object-Oriented Programming in Python

So far we studied data structures and functional programming. Now let’s start learning object-oriented programming. Today, we will learn about classes in Python.

Python Classesclasses in python

Python is an object-oriented language and everything in it is an object. By using Python classes and objects, we can model the real world. A class is like a blueprint for objects – it has no values itself. It is an abstract data type. We can have multiple objects of one class.

Defining a Class in Python

To define a class, we use the class keyword, not the def keyword we used to define functions.

Let’s take an example.

Code:

>>> class Fruit:
  pass

This was an empty class. Now let’s declare a variable in it.

Code:

>>> class Fruit:
  name=’fruit’

This is a class Fruit. We use PascalCase to name classes here.

And because Python does not use curly braces, you need to indent the block of code in the class. Without that, it will raise an exception.

Creating an Object in Python

There is no need to use the new keyword for creating objects in Python. Just use this class constructor:

Code:

>>> orange=Fruit()
>>> orange.name

Output:

‘Fruit’

This calls the __init__() method in the Fruit class. We did not declare it, but it uses the default one.

Python classes can also have docstrings to explain what they do. But if you add a docstring to a class, it should be the first thing in the class.

Code:

>>> class MyClass:
  '''This class does nothing'''
  pass

Code:

>>> MyClass
<class '__main__.MyClass'>

The __init__() Method

So what is __init__()?

In most cases, we will need the __init__() method for classes. This is a magic method (dunder method) which we can use to initialize values for classes (objects). So __init__() has initialization code. Every class has __init__ and this is executed when we instantiate the class. You can also use this method to do anything you want to do when the object is being created. Let’s learn with an example.

Code:

>>> class Fruit:
  def __init__(self, color, size):
    self.name='fruit'
    self.color=color
    self.size=size

1. Accessing Values

We have created the class, now let’s learn to create an object for it and access its values.

Code:

>>> orange=Fruit('orange',8)
>>> orange.name

Output:

‘fruit’

Code:

>>> orange.color

Output:

‘orange’

Code:

>>> orange.size

Output:

8

Here, class Fruit has an object orange. This has a name, color, and size. The name for all fruits is name, and color and size are passed as arguments. So orange is the object with color ‘orange’ and size 8. We accessed the values with the dot operator. We will talk about the ‘self’ parameter in the next section.

Python Classes Methods

Python classes can have methods and functions. Functions are simply functions. But methods act on an object and can modify it. Each method has to take the self parameter as the first parameter. It tells it to work on this object. However, you can call it anything you want. Let’s define a method in class Fruit.

Code:

>>> class Fruit:
  def __init__(self, color, size):
    self.name='fruit'
    self.color=color
    self.size=size
  def show(self):
    print(f'I am a {self.name}, I am {self.color} and of size {self.size}')

Code:

>>> orange=Fruit('orange',8)

Now, we can call the show() method on the orange object. For this, we use the dot operator.

Code:

>>> orange.show()

Output:

I am a fruit, I am orange and of size 8

You can call the self parameter anything.

Code:

>>> class Fruit:
  def __init__(obj, color, size):
    obj.name='fruit'
    obj.color=color
    obj.size=size
  def show(obj):
    print(f'I am a {obj.name}, I am {obj.color} and of size {obj.size}')

Code:

>>> orange=Fruit('orange',8)
>>> orange.show()

Output:

I am a fruit, I am orange and of size 8

You also have to use the self parameter even when a method does not take any parameters.

Changing Object Properties

We use the dot operator to access object properties and methods, but we can also use it to modify them.

Code:

>>> orange.size=9
>>> orange.size

Output:

9

And we can also delete them with the del keyword.

Code:

>>> del orange.size
>>> orange.size

Output:

Traceback (most recent call last):
  File “<pyshell#33>”, line 1, in <module>
    orange.size
AttributeError: ‘Fruit’ object has no attribute ‘size’

We can also delete the complete object with the del keyword.

Code:

>>> del orange
>>> orange.size

Output:

Traceback (most recent call last):
  File “<pyshell#35>”, line 1, in <module>
    orange.size
NameError: name ‘orange’ is not defined

Python Class Variables

Classes create new local namespaces with their attributes (data or functions). You can make a variable belong to a class. This is not like instance variables which belong to objects.

Code:

>>> class Fruit:
  name='fruit'
  def __init__(obj, color, size):
    obj.color=color
    obj.size=size
  def show(obj):
    print(f'I am a {obj.name}, I am {obj.color} and of size {obj.size}')

Code:

>>> orange=Fruit('orange',8)
>>> orange.name

Output:

‘fruit’

Here, the class Fruit has the class variable ‘orange’, but the orange object also has it.

1. Built-in Class Attributes

Python has some built-in class attributes that we can use to get more information about the class.

1.1. __dict__ – It is a dictionary consisting of the class’ namespace.

Code:

>>> Fruit.__dict__

Output:

mappingproxy({‘__module__’: ‘__main__’, ‘__init__’: <function Fruit.__init__ at 0x0000023450FB0048>, ‘show’: <function Fruit.show at 0x0000023450FB00D0>, ‘__dict__’: <attribute ‘__dict__’ of ‘Fruit’ objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘Fruit’ objects>, ‘__doc__’: None})

1.2. __doc__ – It is the class docstring, but is None if there is no docstring in the class.

Code:

>>> Fruit.__doc__

Output:

>>>

1.3. __name__ – This is the class name.

Code:

>>> Fruit.__name__

Output:

‘Fruit’

1.4. __module__ – This is the name of the module in which the class is defined. In the interactive mode, this is __main__.

Code:

>>> Fruit.__module__

Output:

‘__main__’

1.5. __bases__ – This is a tuple consisting of the base classes of this class.

Code:

>>> Fruit.__bases__

Output:

(<class ‘object’>,)

Instance Variables in Python

Instance variables belong to objects. We saw an example, but now we will see those other methods that __init__ can define them too.

Code:

>>> class Fruit:
  def __init__(obj, color):
    obj.name='fruit'
    obj.color=color
  def show(obj, size):
    obj.size=size
    print(f'I am a {obj.name}, I am {obj.color} and of size {obj.size}')

Code:

>>> orange=Fruit('orange')
>>> orange.show(8)

Output:

I am a fruit, I am orange and of size 8

Here, we define the size in the show() method using obj.size=size and it works like it should.

Summary

So in this tutorial, we learned about classes in Python. We saw how to define them, create objects, the __init__ method, methods, changing and deleting object properties, class variables, and instance variables. Next, we will deal with objects in detail. Till then, keep practicing.

I hope you found TechVidvan’s Python classes article useful. If you have any queries, do let us know in the comment section.

Happy Learning!!

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.