Python tutorials > Object-Oriented Programming (OOP) > Classes and Objects > What is `self`?

What is `self`?

In Python's object-oriented programming, self is a convention used as the first parameter in instance methods. It refers to the instance of the class on which the method is called. Understanding self is crucial for working with classes and objects effectively.

The Role of `self` in Class Methods

In this example, self is used in the __init__ method to assign the name and breed arguments to the instance's attributes. When dog1.bark() is called, self automatically refers to the dog1 object. Thus, self.name accesses the name attribute of dog1.

The __init__ method is a special method (also called a constructor) and gets automatically called when an object of that class is created.

class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        print(f'{self.name} says Woof!')

dog1 = Dog('Buddy', 'Golden Retriever')
dog1.bark()  # Output: Buddy says Woof!

Concepts Behind the Snippet

When you create an object from a class (instantiation), Python automatically passes the instance (the object itself) as the first argument to any instance method. By convention, this first parameter is named self. It allows the method to access and modify the object's attributes and call other methods on the same object.

Real-Life Use Case

Imagine you're building a game with a Character class. Each character has attributes like health, strength, and position. Methods like move, attack, and take_damage would use self to update these attributes for the specific character instance. For example:

class Character:
    def __init__(self, name, health, strength, position):
        self.name = name
        self.health = health
        self.strength = strength
        self.position = position

    def move(self, distance):
        self.position += distance
        print(f'{self.name} moved to position {self.position}')

    def take_damage(self, damage):
        self.health -= damage
        print(f'{self.name} took {damage} damage. Health is now {self.health}')

hero = Character('Aragorn', 100, 20, 0)
hero.move(10)
hero.take_damage(15)

Here, self allows each Character instance to maintain its own independent state.

Best Practices

  • Always use self as the first parameter name for instance methods. While you could technically use another name, it's a strong convention, and deviating from it makes your code less readable to other Python developers.
  • Use descriptive attribute names. While self.x = something might work, self.name = something or self.age = something are much clearer.

Interview Tip

When asked about self in an interview, emphasize that it's a reference to the instance of the class. Explain how it's automatically passed to instance methods and how it's used to access and modify the object's attributes. Also, mention it is just a convention.

When to Use Them

You use self in every instance method of a class. An instance method is a method which belongs to an object. This is required to access attributes that are specific to that instance. If you write a function inside a class that doesn't need to access the instance’s data, consider making it a @staticmethod or a @classmethod.

Alternatives

There aren't really 'alternatives' to self in the traditional sense. It's fundamental to how Python's object model works. However, different design patterns might reduce the frequency with which you directly manipulate attributes using self, such as using properties with getters and setters for controlled access.

Pros

  • Explicit Instance Reference: self makes it clear that you're working with the instance's attributes, improving code readability.
  • Namespace Management: It helps avoid naming conflicts between local variables and instance attributes.
  • Clear Scope: It explicitly defines the scope of variables being accessed within a class.

Cons

  • Requires Understanding: New programmers sometimes find the concept of self confusing initially.
  • Slight Overhead: There's a minimal performance overhead associated with passing self, but it's negligible in most cases.

FAQ

  • Can I use a different name instead of `self`?

    Technically, yes, you can use a different name. However, it's strongly discouraged. Using self is a well-established convention in Python, and deviating from it will make your code harder to read and understand for other Python programmers. Tools like linters might even flag it as an error.

  • Is `self` a keyword in Python?

    No, self is not a keyword. It's just a convention for naming the first parameter of an instance method. You can technically use another name, but you shouldn't.

  • What happens if I forget to include `self` as the first parameter in a method?

    If you forget to include self as the first parameter, you'll get a TypeError when you call the method on an object. The error message will indicate that the method was called with one argument too few.