2024-04-26 11:48:43 发布
网友
这是实例变量还是类变量?你知道吗
def f(self): # is this instance.f an instance variable? return 'hello world'
instance.f()命令为所有实例返回相同的结果,那么这对于实例还是类来说是唯一的呢?你知道吗
instance.f()
即使它做了一些与特定实例无关的事情,它也总是接收一个不同的实例作为self参数。最好改用静态方法:
self
@staticmethod def f(): return 'hello world'
现在它是独一无二的:
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
即使它做了一些与特定实例无关的事情,它也总是接收一个不同的实例作为
self
参数。最好改用静态方法:现在它是独一无二的:
相关问题 更多 >
编程相关推荐