实例方法

发布: (2026年4月28日 GMT+8 19:47)
2 分钟阅读
原文: Dev.to

Source: Dev.to

实例方法

在学习了类之后,让我们来学习方法。

class Time:
    def __init__(self):
        self.hours = 0
        self.minutes = 0

    def print_time(self):
        print(f'Hours: {self.hours}', end=' ')
        print(f'Minutes: {self.minutes}')


time1 = Time()
time1.hours = 3
time1.minutes = 35
time1.print_time()

在上面的例子中,print_time 是一个 实例方法——在类内部定义的、作用于特定实例的函数。
__init__ 方法是一个特殊的实例方法,它在创建新对象时自动运行,用来初始化对象的属性。

初学者常犯的错误是忘记在方法的第一个参数中加入 self。因为 Python 会自动把实例引用作为第一个参数传入,忘记 self 会导致 “参数过多” 的错误。

常见错误:忘记 self

class Employee:
    def __init__(self):
        self.wage = 0
        self.hours_worked = 0

    def calculate_pay(self):  # `self` 必须包含在内
        return self.wage * self.hours_worked


alice = Employee()
alice.wage = 6.25
alice.hours_worked = 15
print(f'Alice earned {alice.calculate_pay():.2f}')

如果省略了 self 参数(例如 def calculate_pay():),调用 alice.calculate_pay() 时会抛出错误,因为 Python 会自动尝试传入实例,导致参数不匹配。加入 self 即可解决此问题。

0 浏览
Back to Blog

相关文章

阅读更多 »

消息与通知工具比较 (2026)

PostgreSQL LISTEN/NOTIFY ✅ 优点 - 内置于数据库,无需额外安装。 - 严格事务化:只有在数据满足条件时才会发送消息。