SoFunction
Updated on 2024-11-16

Deeper understanding of self, the first parameter of instance methods in python

In object-oriented programming in Python, theself is a frequently encountered term, but for beginners it can be confusing. Why do we need it? How does it work? In this post, we'll dive deeper into theself works and its importance in Python programming.

1. What is self

In Python, theself is an argument to an instance method of a class, representing the instance object of the class itself. In fact, when we call a method of an instance, Python automatically passes that instance as the first argument, which is theself

class Car:
    def __init__(self, brand, model):
         = brand
         = model
    def display(self):
        print(f"This car is a {} {}.")

In the example above, thedisplay method usageself accessbrand cap (a poem)model Properties.

2. Why do we need self?

a. Access to instance attributes and methods

self provides a way for methods of an object to access and manipulate the object's properties. In the aboveCar class, we use the cap (a poem) to access the properties of the instance.

b. Chaining of methods

self Allowing an object's methods to return references to themselves allows us to link method calls.

class Calculator:
    def __init__(self, value=0):
         = value
    def add(self, other_value):
         += other_value
        return self
    def subtract(self, other_value):
         -= other_value
        return self
calc = Calculator()
(5).subtract(3)
print()  # Outputs: 2

3. self is not a keyword

even thoughself is an agreed upon naming convention, but it is not a Python keyword. You can use any other name, but for the sake of code clarity and to follow community conventions, it is recommended to use theself

4. Static and class methods

Not all class methods requireself as its first argument. Static methods and class methods are the two exceptions.

static method: Use@staticmethod Decorator definitions, which do not take any special first argument.

class MyClass:
    @staticmethod
    def my_static_method(arg1, arg2):
        pass

class method: Use@classmethod Decorator definitions, which receive the class as their first argument, are usually namedcls

class MyClass:
    @classmethod
    def my_class_method(cls, arg1, arg2):
        pass

Both static and class methods are methods that are associated with a class rather than its instances. Although they are similar to some extent, they have several major differences. Here are the main differences between static and class methods:

1. Definitions:

  • static method utilization@staticmethod Decorator definition.
  • class method utilization@classmethod Decorator definition.

2. Parameters:

  • static method No specific first argument is required, and they cannot access or modify the state of the class or the state of the instance.
  • class method 's first argument always points to the class itself, not to an instance. This parameter is usually namedcls

3. Calling Methods:

  • static method It can be called from a class or its instances.
  • class method It can also be called from a class or its instances, but no matter how you call it, its first argument is the class itself.

4. Uses:

  • static method Used to perform certain tasks without needing to access the attributes of a class or instance. They are truly "static" and do not depend on the state of the class or instance.
  • class method They are mainly used in scenarios where you need to access class properties or modify the state of a class. For example, they are commonly used for factory methods that return instances of classes.

typical example:

class MyClass:
    class_var = "I'm a class variable"
    def __init__(self, value):
        self.instance_var = value
    @staticmethod
    def static_method():
        return "I'm a static method!"
    @classmethod
    def class_method(cls):
        return f"I'm a class method! Access class_var: {cls.class_var}"
# Use
obj = MyClass("I'm an instance variable")
print(MyClass.static_method())  # exports: I'm a static method!
print(obj.class_method())       # exports: I'm a class method! Access class_var: I'm a class variable

6. Modify class/instance state:

  • static method It is not possible to modify the state of classes or instances because they do not have access to that state.
  • class method It is possible to modify the state of a class, but not the state of an instance directly (unless you explicitly pass an instance).

In general, you should decide whether to use a static or class method based on whether the method needs to access or modify the state of the class or instance. If the method does not need to access that state, then it should probably be a static method. If it needs to access or modify the state of the class, then it should be a class method.

5. self in inheritance

When we use inheritance, theself Represents an instance of the subclass in the subclass, which means that it can access properties and methods defined in both the subclass and the parent class.

class Vehicle:
    def __init__(self, brand):
         = brand
    def display(self):
        print(f"This vehicle is made by {}.")
class Bike(Vehicle):
    def __init__(self, brand, model):
        super().__init__(brand)
         = model
    def display(self):
        super().display()
        print(f"It's a {} bike.")

In this example, theBike classdisplay method first calls the parent class'sdisplay method and then outputs its own information. This is done through theself implementation, which represents both parent and child classes in theBike Examples of.

3. Summary

In object-oriented programming in Python, theself is a core concept that represents instances of objects. This is accomplished through theself, an object's methods can access and modify its properties, call other methods, and support inheritance and polymorphism. Although it is just an ordinary parameter name, it has a special significance in Python programming, providing a foundation for writing clear, structured, and maintainable code.

to this article on the deep understanding of python instance method of the first parameter self of the article is introduced to this, more related python self content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!