python - 类方法和类方法中定义的变量

标签 python class

对于以下代码:

import os.path

class Test:

   @classmethod
   def foo(cls):
       cls.exist = os.path.exists
       print type(cls.exist)
       print type(os.path.exists)

def main():
   Test.foo()

我得到的输出为:

<type 'instancemethod'>
<type 'function'>

我只是将函数 os.path.exist 分配给类变量 cls.exist。 但是当我打印这两个变量时,我得到一个作为实例方法,另一个作为函数。 为什么 ?

最佳答案

您可能将其分配为类变量,但它绑定(bind)到类:

Traceback (most recent call last):
  File "<stdin>", line 12, in <module>
TypeError: unbound method exists() must be called with Test instance as first argument (got str instance instead)

您需要使 exist 成为 staticmethod 才能使其“独立于”类:

cls.exist = staticmethod(os.path.exists)

现在,两者属于同一类型:

<type 'function'>
<type 'function'>

你实际上可以这样调用它:

>>> Test.exist('foo')
False

关于python - 类方法和类方法中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16067188/

相关文章:

python - 为什么回调没有被触发?

Java:扩展对象类

python - 内部服务器错误 Flask

Python - 需要类似字节的对象,而不是 'str'

python - matplotlib 中 Matlab 的 surf(x,y,z,c) 的等价物是什么?

python - 并行化受 CPU 限制的 Python 函数

class - 在 SwiftUI 中将一个 View 的一个 StateObject 类传递给另一 View 的另一个 StateObject 类

php - 当没有类作用域处于事件状态时,无法访问 self::

python - 使用 Python watchdog 生成多个观察者

android - 将动态创建的 RelativeLayout 对齐到 LinearLayout 类中的右侧