When writing classes in Python, you may often encounter the term 'self.'
It is a crucial concept that beginners must understand as they dive deeper into object-oriented features in the Python programming language.
The self
parameter refers to the current instance of a class. You can use it to access the attributes and methods that belong to that class.
In this Python tutorial, we’ll explore how the self
variable plays a pivotal role in Python classes. We’ll also show you how to maintain code clarity, modularity and re-usability through the use of self
.
Understanding Self in Python
Python is an Object-Oriented Programming (OOP) language that heavily relies on classes and objects. So, before diving into the self
parameter, we must first understand what Object Oriented programming is.
Object-Oriented Programming in Python
Object-oriented programming helps programmers model real-world concepts and relationships through the use of classes and objects. This results in code that is more structured, reusable, and scalable.
Think of a class as a template for creating objects with predefined properties and methods. Also, an object is an instance of a class that stores its own values for the attributes and has access to class functions.
These two concepts are an important building block in many Python applications. You can see both classes and objects at work in this video on How To Easily Create Data With Python Faker Library.
The Role of Python Self
Self
is a reference to the instance of the class in Python. It allows you to access and modify the attributes and methods of a class within its own scope.
Here are a few key points on the use of self
in Python:
Self
is not a reserved keyword in the Python syntax. You can use other names to identify class instances butself
is the most widely used and accepted convention by Python programmers.Self
is used as the first parameter in instance methods to reference the current instance of the class.- You can use
self
to distinguish between instance attributes and local variables, making your code more readable and less buggy. - When calling an instance method, Python automatically passes the instance as the first parameter.
- You must declare the
self
parameter in the__init__()
constructor and all other subsequent function constructors in your class. Failure to do so will lead to your program throwing atypeerror
.
You can see an example of this error below:
class Person:
def __init__(self):
print('welcome')
def show_person():
print('I love pandas.')
a = Person()
b = a.show_person()
Traceback (most recent call last):
File "person.py", line 10, in <module>
trill = b.show_person()
^^^^^^^^^^^^^^^^^^
TypeError: Person.show_person() takes 0 positional arguments but 1 was given
Note: You can get around using the self
parameter in functions by using the static method feature that Python 3 provides. We’ll go into more detail on that in a later section.
Working with Self
Learning how to use self is very important to building classes in Python. Throughout this section, you’ll learn how to use self
in different scenarios when working with classes and objects.
Initializing Objects with ‘__init__()’
When creating a new instance of a class, the __init__()
method is called to initialize the object’s attributes. The __init__()
method is the class constructor, and it takes the self
parameter as its first argument.
The self
parameter is used within this method to associate the instance attributes with the given arguments.
Here’s an example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 30)
In this example, the init
method takes self
, name
, and age
as parameters during the object’s initialization. The self
parameter refers to the class instance, allowing you to set the name
and age
attributes for the specific object being created.
Using Self in Methods
When defining instance methods in a class, you should include self
as the first parameter. This allows you to access the instance attributes and other methods within the class.
Let’s expand on the previous example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("Hello, my name is " + self.name + " and I'm " + str(self.age) + " years old.")
person1 = Person("Alice", 30)
person1.introduce()
In this example, the introduce()
method includes self
as its first parameter. This enables you to access the object’s name and age attributes and create a personalized introduction.
When calling the method in your code, you don’t need to pass the
self
parameter explicitly. Python takes care of it automatically.
By following these guidelines and understanding the purpose of self
in Python, beginners can effectively work with classes and objects. This let’s them create well-structured code that’s easy to read and maintain.
Common Self Use Cases
There are many ways you can use the self
keyword in your Python code. By understanding these use cases, you will be able to utilize self
effectively in your programs.
Let’s look at some of them:
Accessing Class Attributes
One primary use of self
is to access instance attributes within a class. Instance attributes are specific to an object created from the class and store the object’s data.
Using self
lets you manipulate or access these attributes within class methods. Let’s look at an example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def display_name(self):
print("The dog's name is:", self.name)
In this example, we used self
to access the name attribute of a Dog object within the display_name
method.
Calling Class Methods
Another common use case of self
is to call other class methods from within an instance method. This allows you to reuse code, reduce complexity, and improve readability.
It’s essential to use self
when referring to other methods, as it ensures the correct method is called for the specific instance. Consider the following example:
class Bird:
def __init__(self, species, color):
self.species = species
self.color = color
def show_species(self):
print("The bird species is:", self.species)
def show_info(self):
self.show_species()
print("The bird color is:", self.color)
In the example above, we use self
to call the show_species
method from within the show_info
method. This enables us to display the bird’s species and color in a single call.
Lastly, remember to use self
when accessing instance attributes and calling class methods. Once you understand these use cases, you will be able to write more efficient and organized Python code.
Best Self Practices
When working with self,
there are some conventions you need to follow to avoid problems and bugs in your code. Here are some of them.
Where to Use Self
When defining instance methods, always use the self
parameter as the first parameter. This allows you to access and modify the object’s instance attributes and call other instance methods within the class.
It’s important to use self
when working with object instances in Python. Using it ensures consistent behavior and allows for proper object encapsulation.
For example, consider the following class:
class MyClass:
def __init__(self, my_var):
self.my_var = my_var
Here, the self parameter is used in the __init__
method to initialize the my_var
attribute of the object instance. This way, my_var
becomes an instance-specific attribute.
As a result, it can be accessed and modified using the self reference in other methods of the class.
Naming Conventions for Self
While self
is the conventional name used for the instance in Python, you can technically use any name you like. However, it’s highly recommended that you stick to using self for clarity and consistency with the broader Python community.
Using a different name might cause confusion to those reading and working with your code, especially if they are accustomed to standard naming conventions in Python libraries.
Where Not to Use Self
We already know that the self
parameter provides access to the object instance. However, in some cases, some functions in the class might not require access to the object instance.
In this scenario, the self parameter is not needed. So, Python provides a static method feature for bypassing the self parameter:
Here’s an example:
class Car:
@staticmethod
def print_car():
print('Vroom Vroom')
In the example above, the @staticmethod
function decorator overrides the self
parameter requirement in the method. This way, the function will still run even if there is no object instance passed into it.
Conclusion
In summary, the self parameter in Python refers to the instance of a class and allows you to access its attributes and methods. As a Python developer, it is important to understand the purpose of self and its use in classes and objects.
By using self consistently in your code, you promote readability and maintainability, which enhances the overall quality of your work.
Also, remember that while you might see the term "self"
used frequently in Python, it is not a reserved Python keyword. This differs from programming languages like Javascript and Java, where "this"
is a reserved keyword.
You can name the first parameter in a class method whatever you like; “self
“ is just the preferred convention.