I. Basic Concepts of Python Methods
In Python, a method usually refers to a function defined inside a class, used to describe the behaviors that a class or an object can perform.
For example, let's define a student class:
class Student:
school = "Python Academy"
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"我是 {self.name},今年 {self.age} 岁"
Here two instance methods are defined:
__init__(): initializes the instance attributes.introduce(): describes the self-introduction behavior of a student object.
In addition, Python also provides class methods and static methods, which are used to organize behaviors at different levels.
1. The three basic categories of methods
Three common kinds of methods in Python:
| Method type | Definition style | First parameter | Main purpose |
|---|---|---|---|
| Instance method | Ordinary method definition | self |
Operates on instance state |
| Class method | @classmethod |
cls |
Operates on class state |
| Static method | @staticmethod |
No special requirement | Organizes related utility logic |
Example:
class Example:
def instance_method(self):
print("实例方法")
@classmethod
def class_method(cls):
print("类方法")
@staticmethod
def static_method():
print("静态方法")
How to call them:
obj = Example()
obj.instance_method()
Example.class_method()
Example.static_method()
The core difference among the three kinds of methods is not where the function is defined, but whether automatic parameter binding takes place at call time, and which object it binds to.
II. Instance Methods
Instance methods are the most common method type in Python, mainly used to operate on the data and behavior of a specific instance.
1. Defining an instance method
Instance methods are defined with the ordinary def, usually taking self as the first parameter.
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:
Hello everyone, my name is Alice
I am 20 years old
Where:
selfrefers to the current instance.self.nameaccesses the name of the current instance.self.ageaccesses the age of the current instance.
self is not a Python keyword, but a parameter name established by community convention. In theory, other names could be used, but it is not recommended.
2. How self works
When an instance method is called through an instance, Python automatically binds the instance to the method's first parameter.
For example:
class Student:
def introduce(self):
print(f"当前实例:{self}")
student = Student()
student.introduce()
The following two call styles have the same parameter-binding effect in the ordinary instance method scenario:
student.introduce()
Student.introduce(student)
The first call is more common and more in line with Python's usage habits.
3. The underlying binding mechanism of instance methods
In Python, an ordinary function defined inside a class usually has descriptor behavior.
Accessing it through the class:
class Student:
def introduce(self):
print("Hello")
print(Student.introduce)
What you get is the function object stored in the class.
Accessing it through an instance:
student = Student()
print(student.introduce)
What you get is usually a bound method object.
A bound method stores:
- The original function object.
- The bound instance.
You can inspect it via __self__ and __func__:
class Student:
def introduce(self):
print("Hello")
student = Student()
method = student.introduce
print(method.__self__ is student)
print(method.__func__ is Student.introduce)
Output:
True
True
This shows that instance methods do not simply pass the instance as an argument; rather, they form a bound method through the descriptor protocol.
4. Instance Methods Accessing Instance Attributes
The most typical use of instance methods is to read or modify instance state.
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("存款金额必须大于零")
self.balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("取款金额必须大于零")
if amount > self.balance:
raise ValueError("余额不足")
self.balance -= amount
def get_balance(self):
return self.balance
account = Account("Alice", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
Output:
1300
Here, deposit() and withdraw() both need to access the current account balance, so they are suitable to be defined as instance methods.
5. Instance Methods Can Call Other Instance Methods
class User:
def __init__(self, name):
self.name = name
def validate_name(self):
return bool(self.name.strip())
def introduce(self):
if not self.validate_name():
return "用户名无效"
return f"你好,{self.name}"
user = User("Alice")
print(user.introduce())
Output:
你好,Alice
Instance methods can call one another through self, allowing complex behavior to be split into smaller logical units.
6. When to Use Instance Methods
Situations where instance methods are appropriate:
- Reading instance attributes.
- Modifying instance state.
- Executing business logic related to the current object.
- Calling other instance methods.
- Operating on resources held by the current object.
Typical example:
class Order:
def __init__(self, order_id, amount):
self.order_id = order_id
self.amount = amount
self.status = "pending"
def pay(self):
if self.status != "pending":
raise ValueError("当前订单不能支付")
self.status = "paid"
def cancel(self):
if self.status == "paid":
raise ValueError("已支付订单不能直接取消")
self.status = "cancelled"
Paying and canceling an order both depend on the state of a specific order instance, so instance methods should be used.
III. Class Methods (Class Method)
Class methods are methods bound to the class object. They are mainly used to operate on class-level data and are also often used to implement alternative constructors.
1. Defining Class Methods
Python uses the @classmethod decorator to define class methods.
class Student:
school = "Python Academy"
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
Output:
Python Academy
Here:
@classmethodindicates that the method is defined as a class method.clsrepresents the currently bound class.cls.schoolis used to access the class attribute.
Like self, cls is also a conventional parameter name, not a Python keyword.
2. How cls Works
A class method can be called through the class name:
class Student:
school = "Python Academy"
@classmethod
def get_school(cls):
return cls.school
print(Student.get_school())
It can also be called through an instance:
student = Student()
print(student.get_school())
Whether it is called through the class or through an instance, the first parameter of a class method is bound to the corresponding class, not to the instance.
For example:
class Student:
@classmethod
def show_class(cls):
print(cls)
student = Student()
Student.show_class()
student.show_class()
In both calls, cls points to the Student class.
3. Class Methods Accessing Class Attributes
Class methods are very well suited to working with class-level data.
class Employee:
company = "Open Technology"
employee_count = 0
def __init__(self, name):
self.name = name
type(self).employee_count += 1
@classmethod
def get_company(cls):
return cls.company
@classmethod
def get_employee_count(cls):
return cls.employee_count
employee1 = Employee("Alice")
employee2 = Employee("Bob")
print(Employee.get_company())
print(Employee.get_employee_count())
Output:
Open Technology
2
Using a class method to read a class attribute here makes it clear that the target of the operation is class-level.
Note that inheriting and modifying class attributes involves the subclass namespace. Using cls is usually better suited to an inheritable design than hard-coding the parent class name.
4. Class Methods as Alternative Constructors
A very important use of class methods is to provide different entry points for creating objects.
For example, an ordinary constructor takes a name and an age:
class User:
def __init__(self, name, age):
self.name = name
self.age = age
If the user information comes from a string, you can define an alternative constructor:
class User:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, text):
name, age = text.split(",")
return cls(name, int(age))
user = User.from_string("Alice,25")
print(user.name)
print(user.age)
Output:
Alice
25
Here:
return cls(name, int(age))
creates an instance through the currently bound class.
This is more flexible than writing:
return User(name, int(age))
directly, because it can adapt to inheritance relationships.
5. Class Methods Support Subclass Polymorphism
class Animal:
def __init__(self, name):
self.name = name
@classmethod
def create(cls, name):
return cls(name)
class Dog(Animal):
def bark(self):
return "汪汪"
dog = Dog.create("Lucky")
print(type(dog))
print(dog.name)
print(dog.bark())
Output:
<class '__main__.Dog'>
Lucky
汪汪
When a subclass calls an inherited class method, cls is bound to the subclass.
Therefore, cls(name) creates a Dog instance, not a fixed Animal instance.
This is also why class methods are very valuable in factory methods and inheritance hierarchies.
6. Use Cases for Class Methods
Common scenarios:
- Accessing or modifying class attributes.
- Maintaining class-level statistics.
- Implementing alternative constructors.
- Providing multiple ways to create objects.
- Implementing polymorphic factory methods in inheritance hierarchies.
IV. Static Methods
A static method is a method defined in the class namespace, but it does not automatically receive an instance or class as its first argument.
It is mainly used to organize functions that are logically related to the class but do not need to access instance state or class state.
1. Defining Static Methods
Use the @staticmethod decorator to define a static method.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
print(MathUtils.add(10, 20))
Output:
30
Here, add() does not need to access any instance attributes or class attributes, so it can be defined as a static method.
2. Static Methods Do Not Automatically Receive self or cls
class MathUtils:
@staticmethod
def multiply(a, b):
return a * b
print(MathUtils.multiply(5, 6))
Output:
30
Static methods are not automatically bound to an instance, nor are they automatically bound to a class.
Therefore:
MathUtils.multiply(5, 6)
Only two actual arguments are passed in.
The same is true when called through an instance:
math = MathUtils()
print(math.multiply(5, 6))
It also outputs:
30
3. Static Methods Can Access External Data
Although static methods do not automatically receive an instance or class, they can still use parameters, local variables, module-level variables, and other accessible objects.
TAX_RATE = 0.13
class PriceCalculator:
@staticmethod
def calculate_tax(price):
return price * TAX_RATE
print(PriceCalculator.calculate_tax(100))
Output:
13.0
However, static methods are not suitable for relying on a large amount of external mutable state; otherwise, they reduce the testability and maintainability of the code.
4. Static Methods Can Organize Business Helper Logic
class UserValidator:
@staticmethod
def is_valid_email(email):
return "@" in email and "." in email
@staticmethod
def is_valid_age(age):
return isinstance(age, int) and age >= 18
print(UserValidator.is_valid_email("alice@example.com"))
print(UserValidator.is_valid_age(25))
Output:
True
True
These methods are related to user validation logic, but they do not need to read the state of a specific user instance.
5. Use Cases for Static Methods
Common scenarios:
- Data format validation.
- Mathematical calculations.
- String processing.
- Parameter conversion.
- Helper logic closely related to the class's business logic.
- Utility functions that do not depend on instance or class state.
Note: if a function has no obvious logical belonging to a class, defining it directly as a module-level function is usually more appropriate; there is no need to put every function into a class for the sake of object orientation.
V. Calling and Binding Mechanisms of the Three Method Types
The most critical part of understanding the three method types is mastering Python's descriptor protocol and method binding mechanism.
1. Binding Differences Among the Three Method Types
class Example:
def instance_method(self):
return "实例方法"
@classmethod
def class_method(cls):
return "类方法"
@staticmethod
def static_method():
return "静态方法"
Access via class:
print(Example.instance_method)
print(Example.class_method)
print(Example.static_method)
Access via instance:
obj = Example()
print(obj.instance_method)
print(obj.class_method)
print(obj.static_method)
The three methods have different binding semantics when accessed:
| Method | Accessed via class | Accessed via instance |
|---|---|---|
| Instance method | Plain function | Method bound to instance |
| Class method | Method bound to class | Method bound to class |
| Static method | Original function | Original function |
2. Binding relationship diagram of the three method types
flowchart TD
A["Methods defined in class"] --> B{"Method type"}
B --> C["Instance method"]
B --> D["Class method"]
B --> E["Static method"]
C --> F["Accessed via instance"]
C --> G["Accessed via class"]
F --> H["Binds self"]
G --> I["Requires manually passing an instance"]
D --> J["Accessed via class or instance"]
J --> K["Binds cls"]
E --> L["Accessed via class or instance"]
L --> M["Does not automatically bind parameters"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style J fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style L fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style M fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3. Method binding and the descriptor protocol
In Python, when a regular function is defined in a class, it usually implements the descriptor protocol.
When a regular function is accessed through an instance, the descriptor's __get__() is triggered, producing a bound method.
You can observe this with the following code:
class Example:
def show(self):
print("Hello")
obj = Example()
function = Example.__dict__["show"]
bound_method = obj.show
print(type(function))
print(type(bound_method))
print(bound_method.__self__ is obj)
print(bound_method.__func__ is function)
The output is similar to:
<class 'function'>
<class 'method'>
True
True
Class methods and static methods are also related to the descriptor mechanism:
classmethodprovides descriptor behavior that binds the class to the first parameter.staticmethodprovides access behavior that does not automatically bind an instance or class.
You can inspect them through the class namespace:
```python class Example: def instance_method(self): pass @classmethod def class_method(cls): pass @staticmethod def static_method(): pass print(type(Example.__dict__["instance_method"])) print(type(Example.__dict__["class_method"])) print(type(Example.__dict__["static_method"])) ```Typically you will observe:
<class 'function'>
<class 'classmethod'>
<class 'staticmethod'>
Note that what is being observed here is the object stored in the class namespace, not the bound result you get after accessing it through the class or an instance.
6. The Three Kinds of Methods and Inheritance
Instance methods, class methods and static methods also behave differently within an inheritance hierarchy.
1. Instance methods support inheritance and overriding
class Animal:
def speak(self):
return "动物发出声音"
class Dog(Animal):
def speak(self):
return "汪汪"
dog = Dog()
print(dog.speak())
Output:
汪汪
A subclass can override an instance method of its parent class.