首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python是否认为任何没有cls或自参数的方法都是静态的?

问python是否认为任何没有cls或自参数的方法都是静态的?
EN

Stack Overflow用户
提问于 2015-05-11 10:04:47
回答 2查看 298关注 0票数 1

下面是带有方法的测试类,这些类不使用cls或self参数,也没有@staticmethod装饰符。它们像普通的静态方法一样工作,不抱怨争论。这似乎与我对python方法的理解相反。python是否自动将非类、非实例方法视为静态方法?

代码语言:javascript
复制
>>> class Test():
... def testme(s):
...  print(s)
...
>>> Test.testme('hello')
hello

>>> class Test():
...  def testme():
...   print('no')
...
>>> Test.testme()
no

P.S:我用的是python3.4

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-11 10:11:57

请注意,这在Python 2中不起作用:

代码语言:javascript
复制
>>> class Test(object):
...     def testme():
...         print 'no'
...
>>> Test.testme()
Traceback (most recent call last):
  File "<ipython-input-74-09d78063da08>", line 1, in <module>
    Test.testme()
TypeError: unbound method testme() must be called with Test instance as first argument (got nothing instead)

但是在Python3中,删除了未绑定的方法,正如Alex指出的in this answer。所以,实际上,您所做的就是调用一个在Test类中定义的普通函数。

票数 2
EN

Stack Overflow用户

发布于 2015-05-11 10:11:00

有点像,是的。但是,请注意,如果在实例上调用这样一个“隐式静态方法”,则会得到一个错误:

代码语言:javascript
复制
>>> Test().testme()
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    Test().testme()
TypeError: testme() takes 0 positional arguments but 1 was given

这是因为self参数仍然被传递给,这在正确的@staticmethod中不会发生

代码语言:javascript
复制
>>> class Test:
    @staticmethod
    def testme():
        print('no')


>>> Test.testme()
no
>>> Test().testme()
no
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30164776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档