【发布时间】:2015-12-12 03:56:39
【问题描述】:
这就是我们在 Python 中制作静态函数的方式:
class A:
@staticmethod
def fun():
print 'hello'
A.fun()
这按预期工作并打印hello。
如果是成员函数而不是静态函数,我们使用self:
class A:
def fun(self):
print 'hello'
A().fun()
它也可以按预期工作并打印hello。
我对以下情况感到困惑:
class A:
def fun():
print 'hello'
在上述情况下,没有staticmethod,也没有self。 Python 解释器可以接受这个定义。但是,我们不能将其称为上述任何一种方法,即:
A.fun()
A().fun()
两者都给出错误。
我的问题是:有什么方法可以调用这个函数吗?如果不是,为什么 Python 一开始就不给我语法错误?
【问题讨论】:
标签: python python-2.7 methods static-methods