使用 self 和类名调用方法之间的区别?

d9h*_*d9h 4 python python-3.x

class A:

    def __init__(self, text):
        self.printStats()
        A.printStats(text)

    def printStats(self):
        print(self)

a = A("Hello")
Run Code Online (Sandbox Code Playgroud)

这打印:

<A object at 0x7f47e2f08ac8>
Hello
Run Code Online (Sandbox Code Playgroud)

为什么这 ( A.printStats(text)) 是可能的?我明白发生了什么(self参考文献text),但我不明白为什么。

noɥ*_*ɐɹƆ 5

A.printStats(text)
Run Code Online (Sandbox Code Playgroud)

printStats使用A. 它用一个字符串调用它 - 没有self传递。

def printStats(self):
    # <--- here, "self" if the string "Hello", not an instance of A.
    print(self)
Run Code Online (Sandbox Code Playgroud)

A.printStats(self)相当于self.printStats。同样,如果你有一个函数printStatsWithPrefix

class A:
    def printStatsWithPrefix(self, prefix):
        ...  # function body goes here
Run Code Online (Sandbox Code Playgroud)

你必须这样做A.printStatsWithPrefix(self, prefix)


关于样式的说明:根据 Python 约定 (PEP 8),您应该使用lowercase_with_underscores函数名称。


Pio*_*ski 1

当您创建该类的实例时:

a = A('some text')
Run Code Online (Sandbox Code Playgroud)

参数self永久绑定到a,这就是类背后的魔力。如果您尝试a.printStats('something')这样做,将会引发错误,因为self参数已被 占用a。您可以使用 恢复具有未绑定自身的原始函数a.printFunction.__func__。尝试a.printFunction.__func__('this will be self argument')

但是,当您不创建实例时,没有任何内容可以绑定self,因此self仍然可以使用。在这种情况下,您可以将其A视为保存函数的简单字典。

A = {'__init__': someInitFunction,
     'printStats': printStatsFunction}
Run Code Online (Sandbox Code Playgroud)

您必须记住,该名称self是任意的,您可以使用任何单词,甚至not_self