那么这是一个实例变量还是一个类变量?
def f(self): # is this instance.f an instance variable?
return 'hello world'
Run Code Online (Sandbox Code Playgroud)
该instance.f()命令为所有实例返回相同的内容,因此这对于实例或类是唯一的吗?
即使它执行与特定实例无关的某些操作,它也始终接收不同的实例作为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)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |