在什么情况下我应该使用self关键字



我有一个简单的问题,但它让我困惑了很长一段时间。这是示例代码:

class test():
def func(self):

lst = []
self.num = 0

def method(tmp):
lst.append(tmp)
self.num += 1

method(1)

问题是,为什么我需要在num之前添加self,而对于lst,我不需要这样做?

self.numfunc内部使num全局化?

self是对类实例的引用。因此,self.num引用实例上的属性num,而lst是该方法的局部变量。

class test:
def func(self):
self.lst = [0, 1, 2, 3]
lst = [5, 6, 7, 8]
print(self.lst) # [0, 1, 2, 3]
print(lst) # [5, 6, 7, 8]
def test(self):
print(self.lst) # [0, 1, 2, 3]
print(lst) # Error
i = test()
i.func()
i.test() # Error, see above

如果没有self,代码就无法工作,因为不可变类型与可变类型,但此代码将:

class test():
def func(self):

lst = []
num = 0

def method(tmp):
nonlocal num
lst.append(tmp)
num += 1

method(1)

这是因为列表是可变的,因此在编辑lst的值时不会进行复制。而当num的值发生变化时,它将生成一个新的变量(局部num(。参见文档非本地

请注意,您不能访问func之外的num。因此,这将不起作用(而它以前会(

t = test()
t.func()
print(t.num) # doesn't exist!

func是类的成员函数。method只是一个独立的函数,与类无关。为了呼叫func,您必须说:

obj.func()

Python通过自动传递obj作为第一个参数来处理这个问题,我们传统上称之为self。但要呼叫method,您只需说:

method(1)

没有对象,因此没有自动创建第一个参数。当您在method内部引用selfnum时,您指的是它继承的外部函数中的局部变量。

最新更新