我刚接触Python,有Java背景,函数中的“self”概念让我很困惑。我理解第一个参数“self”是指对象本身,但我不理解Python是如何实现这一点的。我也知道我可以使用“this”或“that”或“somethingElse”,Python仍然理解我使用对象的意思。你知道吗
我从reddit post复制了一些代码:
class A():
def __init__(self):
self.value = ""
def b(this):
this.value = "b"
def c(that):
that.value = "c"
a = A()
print(a.value)
a.b()
print(a.value)
>>>"b"
a.c()
print(a.value)
>>>"c"
python怎么知道我不是在第一个参数中使用对象的?例如,我稍微修改了上面的代码:
class A():
def __init__(self):
self.value = ""
def b(this):
this.value = "b"
def c(that):
that.value = "c"
def somethingElse(someObjectIWantToPass):
someObjectIWantToPass.value = "still referring A.value"
class B():
def __init__(self):
self.value = ""
a = A()
print(a.value)
a.b()
print(a.value)
a.c()
print(a.value)
a.somethingElse()
print(a.value)
b = B()
a.somethingElse(b)
print (b.value)
它坏了:
b
c
still referring A.value
Traceback (most recent call last):
File "D:/Documents/test.py", line 32, in <module>
a.somethingElse(b)
TypeError: somethingElse() takes 1 positional argument but 2 were given
你太注重句法上的糖分了。只需了解python中非静态成员函数的第一个参数是对当前对象的引用。不管你想叫它
this
、that
、foobar
、poop
,都无所谓。成员函数的第一个参数被认为是对调用方法的对象的引用。你知道吗使用
self
只是每个人理解它的一种普遍方式,Python
推荐的方式——如果可以的话,可以是一种约定。你知道吗这同样适用于
**kwargs
和*args
。这些只是渗透到Python生态系统中的约定,每个人都是这样使用的,但这并不意味着不能给它们起不同的名字。你知道吗上一个示例中断,因为您正在调用的函数(
A.something
)没有任何参数。如果您理解我前面所说的关于非静态成员函数中的第一个参数是对调用该方法的对象的引用的话,这将是有意义的。你知道吗方法的第一个参数始终是它的实例。在Python中称之为
self
是惯用的,但这个名称严格按照惯例。你知道吗如果您试图传入另一个任意对象,它必须是第二个参数。你知道吗
实际上并不总是这样。
@classmethod
修饰的方法使用cls
作为它们的第一个参数,并且@staticmethod`修饰的方法在默认情况下没有传递给它的第一个参数。你知道吗相关问题 更多 >
编程相关推荐