类中的每个函数都是`self`一个实例变量,即使它只是做与特定实例无关的事情吗?

Sla*_*ade 0 python

那么这是一个实例变量还是一个类变量?

def f(self):   # is this instance.f an instance variable?
    return 'hello world'
Run Code Online (Sandbox Code Playgroud)

instance.f()命令为所有实例返回相同的内容,因此这对于实例或类是唯一的吗?

cdo*_*nts 5

即使它执行与特定实例无关的某些操作,它也始终接收不同的实例作为self参数.使用静态方法可能更好:

@staticmethod
def f():
    return 'hello world'
Run Code Online (Sandbox Code Playgroud)

现在它是独一无二的:

class C:
    def f(self):
        return 'hello world'

a = C()
b = C()
print(a.f == b.f)  # False

class C:
    @staticmethod
    def f():
        return 'hello world'

a = C()
b = C()
print(a.f == b.f)  # True
Run Code Online (Sandbox Code Playgroud)