Skip to content

方法

一句话解释

方法 是 函数 定义 内部 类 那个 操作 on 实例 的 那个 类 通过 self.

用大白话说

方法是 函数那个 belongs 到类. 它是 定义内部类 请求体 and takes self as its first parameter, which refers to the instance the method is called on.

When you call obj.方法(args), Python automatically passes obj as self. This lets the method access and modify the object's attributes. Methods can also return values, just like regular functions.

Special methods (dunder methods) have double underscores, like __init__ (constructor), __str__ (string representation), __len__ (length), and *__eq__ (equality comparison). These define how objects behave with built-in operations.

示例

python
class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount
        return self.balance

    def __str__(self):
        return f"Account(balance={self.balance})"

acct = BankAccount(100)
print(acct.deposit(50))  # 150
print(acct)              # Account(balance=150)

方法 是 类 函数 using self. 特殊 dunder 方法 如 __str__ 定义 构建-in behavior.

常见混淆

  • 容易混淆的对象: 函数

    关键区别: 方法 是 函数 定义 内部 类 and called on 实例 (obj.方法()). 函数 是 standalone. 方法 有 implicit 'self' 参数; 函数 做 不.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表