What is self in Python?
In Python, 'self' is a conventional name for the first parameter of instance methods, referring to the instance of the class itself. It allows methods to access and modify the instance's attributes and call other instance methods.
What is 'self'?
The 'self' parameter in Python is a reference to the current instance of the class. It is always the first parameter in any instance method definition, though it does not need to be named 'self' (it's a convention, not a keyword). When a method is called on an object, Python automatically passes that object as the first argument to the method.
Its primary purpose is to allow instance methods to access the instance's attributes (variables belonging to the object) and other instance methods. Without 'self', a method wouldn't know which specific object's data it should operate on.
Why 'self' is used
Unlike some other object-oriented languages (like Java or C++), Python does not have a special keyword to refer to the current instance. Instead, it relies on this explicit 'self' parameter. This design choice makes it clear that you are working with instance-specific data and helps distinguish instance variables from local variables.
While 'self' is a widely accepted and strong convention, you could technically name it something else (e.g., 'this' or 'instance_of_me'). However, deviating from 'self' is strongly discouraged as it significantly reduces code readability and maintainability for other Python developers.
Example
class Dog:
def __init__(self, name, breed):
self.name = name # 'self.name' refers to the instance's 'name' attribute
self.breed = breed # 'self.breed' refers to the instance's 'breed' attribute
def bark(self):
print(f"{self.name} says Woof!") # 'self.name' is accessed here
def get_description(self):
return f"{self.name} is a {self.breed}."
# Creating instances of the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Beagle")
# Calling instance methods
my_dog.bark() # Output: Buddy says Woof!
print(my_dog.get_description()) # Output: Buddy is a Golden Retriever.
your_dog.bark() # Output: Lucy says Woof!
print(your_dog.get_description()) # Output: Lucy is a Beagle.
In the example above, 'self' is used in the '__init__' method to assign the passed 'name' and 'breed' arguments to instance-specific attributes ('self.name', 'self.breed'). It's also used in 'bark' and 'get_description' methods to access these attributes and operate on the specific 'Dog' instance that called the method.
Key Takeaways
- 'self' is the conventional first parameter of instance methods.
- It refers to the instance of the class (the object itself).
- It allows methods to access instance attributes and other instance methods.
- It is not a Python keyword but a widely adopted convention for clarity and readability.
- When you call a method on an object (e.g., 'obj.method()'), Python automatically passes 'obj' as the 'self' argument to 'method'.