为什么要理解“自我”、“这个”和“那个”?

2024-10-02 10:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚接触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

Tags: 对象代码self参数thatinitvaluedef
2条回答

你太注重句法上的糖分了。只需了解python中非静态成员函数的第一个参数是对当前对象的引用。不管你想叫它thisthatfoobarpoop,都无所谓。成员函数的第一个参数被认为是对调用方法的对象的引用。你知道吗

使用self只是每个人理解它的一种普遍方式,Python推荐的方式——如果可以的话,可以是一种约定。你知道吗

这同样适用于**kwargs*args。这些只是渗透到Python生态系统中的约定,每个人都是这样使用的,但这并不意味着不能给它们起不同的名字。你知道吗


上一个示例中断,因为您正在调用的函数(A.something)没有任何参数。如果您理解我前面所说的关于非静态成员函数中的第一个参数是对调用该方法的对象的引用的话,这将是有意义的。你知道吗

方法的第一个参数始终是它的实例。在Python中称之为self是惯用的,但这个名称严格按照惯例。你知道吗

class A():
    def some_method(me):  # not called `self`
        print(str(id(me))

a = A()
a.some_method()
print(id(a))

如果您试图传入另一个任意对象,它必须是第二个参数。你知道吗

class B():
    def another_method(self, other):
        print(id(other))

b = B()
b.another_method(a)
print(id(b))  # different!
print(id(a))  # the same.

实际上并不总是这样。@classmethod修饰的方法使用cls作为它们的第一个参数,并且@staticmethod`修饰的方法在默认情况下没有传递给它的第一个参数。你知道吗

class C():
    @classmethod
    def some_classmethod(cls, other, arguments):
        # first argument is not the instance, but
        # the class C itself.

    @staticmethod
    def something_related(other, arguments):
        # the first argument gets neither the instance
        # nor the class.

相关问题 更多 >

    热门问题