在 Python 中,'self' 是一个特殊的参数,用于表示类的实例对象本身。在类中定义方法时,第一个参数必须是 'self',用于引用当前实例对象。通过 'self' 可以访问实例对象的属性和方法。

例如,假设我们有一个名为 Person 的类,其中有一个名为 say_hello 的方法:

class Person:
    def __init__(self, name):
        self.name = name
    
    def say_hello(self):
        print('Hello, my name is', self.name)

在上面的代码中,'init' 方法用于初始化实例属性,say_hello 方法用于打印实例属性 name 的值。

我们创建一个 Person 实例,并调用 say_hello 方法:

p = Person('John')
p.say_hello()

输出结果为:

Hello, my name is John
Python 中 self 的用法详解

原文地址: https://www.cveoy.top/t/topic/nXJj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录