I. What Are self and cls
In Python, self and cls are not keywords; they are conventional parameter names.
They refer to objects at different levels:
| Parameter | Object represented | Where it is commonly used | Main purpose |
|---|---|---|---|
self |
The current instance object | Instance methods | Access instance attributes and instance methods |
cls |
The current class object | Class methods | Access class attributes and class methods |
In simple terms:
selfrepresents a specific object that has been created.clsrepresents the class the object belongs to, or the class currently being called.
For example:
class Person:
species = "Human"
def __init__(self, name):
self.name = name
def introduce(self):
print(f"My name is {self.name}")
@classmethod
def show_species(cls):
print(cls.species)
person = Person("Alice")
person.introduce()
Person.show_species()
Output:
My name is Alice
Human
Here:
self.nameaccesses thenameattribute of the current instance.cls.speciesaccesses thespeciesattribute of the current class.
II. The Meaning and Role of self
self is the first parameter in an instance method, used to receive the instance object that calls the method.
When an instance method is called through an instance, Python automatically binds the instance object as the method's first parameter.
1. self Represents the Current Instance
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"姓名:{self.name}")
print(f"年龄:{self.age}")
student = Student("Alice", 20)
student.introduce()
Output:
姓名:Alice
年龄:20
In the introduce() method, self points to the current student instance.
Therefore:
self.name
is in fact accessing the name attribute of the current instance.
2. self Is Not a Python Keyword
Python does not require that the first parameter of an instance method be named self.
The following code is also syntactically valid:
class Student:
def __init__(this, name):
this.name = name
def introduce(this):
print(this.name)
student = Student("Alice")
student.introduce()
Output:
Alice
However, this style does not conform to the general convention of the Python community.
It is recommended to always use self, because it lets other developers quickly recognize the current instance.
3. self Is Used to Access Instance Attributes
Instance attributes are usually defined and accessed in the form self.attribute.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def show_balance(self):
print(self.balance)
account = Account("Alice", 1000)
account.deposit(500)
account.show_balance()
Output:
1500
Here:
self.ownerstores the account owner.self.balancestores the current account balance.self.balance += amountmodifies the balance of the current instance.
4. Different instances have different self
class User:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}")
user1 = User("Alice")
user2 = User("Bob")
user1.greet()
user2.greet()
Output:
Hello, Alice
Hello, Bob
Although the two instances call the same method, the self received when the method executes is different.
Therefore, the same instance method can operate on the separate data of different instances.
III. The automatic binding mechanism of self
The most important thing for understanding self is understanding Python's method binding mechanism.
1. Calling a method through an instance
class Person:
def introduce(self):
print("Hello")
person = Person()
person.introduce()
Call:
person.introduce()
Python automatically passes person as the first argument.
Conceptually, this can be understood as:
Person.introduce(person)
The two ways of calling have the same core effect in this example.
2. Calling an instance method through the class
You can also call an instance method directly through the class:
class Person:
def introduce(self):
print("Hello")
person = Person()
Person.introduce(person)
Output:
Hello
At this point, the instance object must be passed explicitly, because when a normal function is accessed through the class, it is not automatically bound to a specific instance.
If the argument is omitted:
Person.introduce()
a TypeError will occur, because the required self argument is missing.
3. Instance method binding process
flowchart TD
A["Define an instance method"] --> B["Access the method through an instance"]
B --> C["Get the function descriptor"]
C --> D["Create a bound method"]
D --> E["Bind the current instance self"]
E --> F["Call the method"]
F --> G["Execute the method body"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
In Python, a normal function has descriptor behavior when it is a class attribute.
When a normal function is accessed through an instance, the function's descriptor mechanism creates a bound method and uses the instance as the first argument.
You can observe this with the following code:
class Person:
def introduce(self):
print("Hello")
person = Person()
print(Person.introduce)
print(person.introduce)
The output is similar to:
<function Person.introduce at ...>
<bound method Person.introduce of <__main__.Person object at ...>>
The difference is:
Person.introduceis the function object on the class.person.introduceis a method object bound to a specific instance.
4. Using self and func to observe bound methods
Bound method objects provide two important attributes:
__self__: the instance to which the method is bound.__func__: the original function object.
class Person:
def introduce(self):
print("Hello")
person = Person()
method = person.introduce
print(method.__self__ is person)
print(method.__func__ is Person.introduce)
Output:
True
True
This shows that a bound method is not simply a copy of the function; rather, it associates the function with an instance.
IV. Meaning and Role of cls
cls is usually used as the first parameter of a class method and represents the current class object.
Class methods are defined with the @classmethod decorator.
class Person:
species = "Human"
@classmethod
def show_species(cls):
print(cls.species)
Person.show_species()
Output:
Human
Here, cls refers to the Person class.
1. cls represents the current class
class Animal:
category = "动物"
@classmethod
def show_category(cls):
print(cls.__name__)
print(cls.category)
Animal.show_category()
Output:
Animal
动物
Where:
cls.__name__
represents the name of the current class.
And:
cls.category
accesses an attribute of the current class.
2. cls is not a Python keyword
Like self, cls is also a conventional name.
class Person:
@classmethod
def show(this_class):
print(this_class.__name__)
Person.show()
Output:
Person
Although the code runs, it is recommended to use cls consistently.
3. cls is commonly used to access class attributes
class Configuration:
environment = "development"
debug = True
@classmethod
def show_config(cls):
print(cls.environment)
print(cls.debug)
Configuration.show_config()
Output:
development
True
Class methods access class-level data through cls.
Note that class attributes can also be accessed through instances, but class methods are more suitable for expressing operations related to the class itself.
V. Automatic Binding Mechanism of cls
Like instance methods, class methods also have an automatic binding mechanism.
The difference is:
- Instance methods automatically bind to the instance object.
- Class methods automatically bind to the class object.
1. Calling a class method through the class
class Person:
@classmethod
def show(cls):
print(cls)
Person.show()
Output:
<class '__main__.Person'>
When called, Python automatically passes Person as the first argument.
Conceptually, this can be understood as:
Person.show()
being equivalent to:
Person.__dict__["show"].__get__(None, Person)()
This shows an expression of the descriptor binding mechanism.
For classmethod, it can also be simply understood as:
Person.show(Person)
However, the actual access process also involves descriptor binding behavior.
2. Calling a class method through an instance
class Person:
@classmethod
def show(cls):
print(cls.__name__)
person = Person()
person.show()
Output:
Person
Although it is called through an instance, a class method still receives the class object, not the instance object.
Therefore, class methods do not depend on a specific instance.
3. Class Method Binding Process
flowchart TD
A["Define class method"] --> B["Apply classmethod decorator"]
B --> C["Access via class or instance"]
C --> D["Execute class method descriptor"]
D --> E["Bind current class cls"]
E --> F["Call method"]
F --> G["Execute method body"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
VI. Differences Between self and cls in Inheritance
Inheritance is an important scenario for understanding self and cls.
In an inheritance hierarchy, methods of the parent class can be inherited by subclasses, but the object received when the method is executed depends on how it is called.
1. self in Inheritance
class Animal:
def speak(self):
print("动物发出声音")
class Dog(Animal):
pass
dog = Dog()
dog.speak()
Output:
动物发出声音
Although speak() is defined in Animal, the instance calling it is dog.
Therefore, self points to an instance of Dog.
Further verification:
class Animal:
def show_type(self):
print(type(self).__name__)
class Dog(Animal):
pass
dog = Dog()
dog.show_type()
Output:
Dog
This shows that inherited methods can still operate on subclass instances.
2. cls in Inheritance
class Animal:
@classmethod
def show_class(cls):
print(cls.__name__)
class Dog(Animal):
pass
Animal.show_class()
Dog.show_class()
Output:
Animal
Dog
Here:
Animal.show_class()binds toAnimal.Dog.show_class()binds toDog.
Although the class method is defined in the parent class, when it is called through a subclass, cls points to the subclass.
This allows class methods to execute different logic depending on the class actually used to call them.
3. Using cls to Implement Polymorphic Instance Creation
Class methods are often used to implement factory methods.
class Person:
def __init__(self, name):
self.name = name
@classmethod
def create_guest(cls):
return cls("Guest")
class Employee(Person):
def __init__(self, name):
super().__init__(name)
self.role = "employee"
person = Person.create_guest()
employee = Employee.create_guest()
print(type(person).__name__)
print(type(employee).__name__)
print(employee.name)
print(employee.role)
Output:
Person
Employee
Guest
employee
Key code:
return cls("Guest")
Here, it does not hard-code Person("Guest"); instead, it uses cls to create the object.
Therefore, when a subclass inherits this class method and calls it, the object created is an instance of the subclass.
This is a very practical inheritance design pattern.
VII. Differences Between self, cls, and Static Methods
In addition to instance methods and class methods, Python also has static methods.
Static methods are defined with the @staticmethod decorator and are not automatically bound to an instance or class object.
class Calculator:
def add(self, a, b):
return a + b
@classmethod
def describe(cls):
return f"当前类:{cls.__name__}"
@staticmethod
def multiply(a, b):
return a * b
Differences among the three types of methods:
| Method Type | First Parameter | Automatically Bound Object | Main Purpose |
|---|---|---|---|
| Instance method | self |
Instance | Operate on instance state |
| Class method | cls |
Class | Operate on class-level state or create instances |
| Static method | No fixed requirement | Not bound | Organize independent functions related to class logic |
Example calls:
calculator = Calculator()
print(calculator.add(2, 3))
print(Calculator.describe())
print(Calculator.multiply(2, 3))
Output:
5
当前类:Calculator
6
1. When Are Instance Methods Appropriate?
Use an instance method when the method needs to access or modify instance attributes.
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
deposit() must know which account is currently being operated on, so it needs self.
2. When Are Class Methods Appropriate?
Use a class method when the method needs to access class attributes, create an instance based on the current class, or implement an alternative constructor.
class User:
def __init__(self, name):
self.name = name
@classmethod
def from_dict(cls, data):
return cls(data["name"])
user = User.from_dict({"name": "Alice"})
print(user.name)
from_dict() does not require an existing instance, but it needs to know what the current class is, so it uses cls.
3. When Are Static Methods Appropriate?
Use a static method when the method is related to the class's business domain but neither needs to access instance state nor class state.
class User:
@staticmethod
def validate_email(email):
return "@" in email
print(User.validate_email("alice@example.com"))