gpt4 book ai didi

python局部变量与 self

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:37 25 4
gpt4 key购买 nike

下面代码中self.x+self.yx+y有什么区别?

class m2:
x, y = 4, 5
def add(self, x, y):
return self.x + self.y
def add2(self, x, y):
return x + y

>>> x = m2()
>>> print "x.add(self.x + self.y = )", x.add(1, 2)
x.add(self.x + self.y = ) 9
>>> print "x.add2(x + y = )", x.add2(1, 2)
x.add2(x + y = ) 3

为什么 self.x + self.y 返回 9x + y 返回 3

最佳答案

add 中,您正在调用类变量并忽略方法参数 xy

class m2:

# these variables are class variables and are accessed via self.x and self.y
x, y = 4, 5

def add(self, x, y):
return self.x + self.y # refers to 4 and 5

def add2(self, x, y):
return x + y # refers to input arguments x and y, in your case 1 and 2

在类作用域中定义 xy 时,它们使它们成为类变量。它们是 m2 类的一部分,您甚至不需要创建 m2 的实例来访问它们。

print m2.x, m2.y
>> 4, 5

但是,您也可以通过实例访问它们,就像它们是这样的实例变量一样:

m = m2()
print m.x, m.y
>> 4, 5

这背后的原因是解释器将查找名称为 self.xself.y 的实例变量,如果没有找到,它将默认为类变量。

阅读更多关于 python 中类属性的信息 documentation .

关于python局部变量与 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35657442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com