Python Classes – Learn Object-Oriented Programming in Python
In this article, we’ll explore the fundamentals of object-oriented programming (OOP). OOP is a programming model that organizes software design around data, or objects, rather than functions and logic. This approach allows for more modular, reusable, and flexible code. An object can be defined as a data field that possesses unique attributes and behavior, encapsulating both data and methods that operate on the data.
Today, we will delve into classes in Python, which are the blueprints for creating objects. By understanding how to define and use classes, you’ll gain the skills to build more complex and organized Python programs.
Python Classes
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:
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:
Code:
>>> orange.color
Output:
Code:
>>> orange.size
Output:
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 both methods and functions. Functions are standalone and not associated with an object. However, methods are functions that belong to an object and can modify its state. Each method in a class must take the self parameter as the first parameter. This parameter refers to the instance of the class, allowing the method to access and modify the object’s attributes. You can name this parameter anything you like, but by convention, it is always named self.
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:
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:
You also have to use the self parameter even when a method does not take any parameters.
Changing Object Properties
In Python classes, 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:
And we can also delete them with the del keyword.
Code:
>>> del orange.size >>> orange.size
Output:
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:
File “<pyshell#35>”, line 1, in <module>
orange.size
NameError: name ‘orange’ is not defined
Python Class Variables
The Python 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:
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.
a. __dict__ – It is a dictionary consisting of the class’ namespace.
Code:
>>> Fruit.__dict__
Output:
b. __doc__ – It is the class docstring, but is None if there is no docstring in the class.
Code:
>>> Fruit.__doc__
Output:
>>>
c. __name__ – This is the class name.
Code:
>>> Fruit.__name__
Output:
d. __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:
e. __bases__ – This is a tuple consisting of the base classes of this class.
Code:
>>> Fruit.__bases__
Output:
Instance Variables in Python
In python classes, 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:
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 python classes.