为什么python理解"自我","这个"和"那个"?

lam*_*988 -1 python

我是Java新手,具有Java背景,功能上的"自我"概念令我困惑.我理解第一个参数"self"意味着对象本身,但我不明白Python如何使这个工作.我也知道我可以使用"this"或"that"或"somethingElse",Python仍然会理解我的意思是使用该对象.

我从reddit 帖子中复制了一些代码:

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"
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

它打破了:

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
Run Code Online (Sandbox Code Playgroud)

Ada*_*ith 6

方法的第一个参数始终是1的实例.self在Python中调用它是惯用的,但该名称是严格遵守的.

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

a = A()
a.some_method()
print(id(a))
Run Code Online (Sandbox Code Playgroud)

如果你试图传递另一个任意对象,它必须是第二个参数.

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.
Run Code Online (Sandbox Code Playgroud)

1实际上并非如此.@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.
Run Code Online (Sandbox Code Playgroud)

  • *总是*除非用*classmathod*或*staticmethod*装饰? (2认同)
  • @StephenRauch*总是*为了这个答案的目的,但我会写一个脚注. (2认同)