【问题标题】:What happens when calling a unbound function during class definition在类定义期间调用未绑定函数会发生什么
【发布时间】:2018-11-22 02:07:06
【问题描述】:

我正在尝试通过调用函数来初始化类属性。请看下文。 这段代码按预期工作,同时让我感到困惑。 据我了解,getmemtoto 是一个所谓的未绑定函数,需要使用类 T 的实例调用。在类定义期间如何调用它?

class T:
    def getmemtot():
        output=shell(r"sed -r -n -e 's/^MemTotal:\s*([[:digit:]]+)\s*kB/\1/ p' /proc/meminfo")
        return int(output)
    MEMTOT=T.getmemtot()

如果我尝试直接调用 getmemtot,则会出现以下错误:

>>> T.getmemtot()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method getmemtot() must be called with T instance as first argument (got nothing instead)
>>> getmemtot()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'getmemtot' is not defined

【问题讨论】:

  • 什么是 ProcEvent?
  • @DanielRoseman 抱歉,我将类名更改为 T 以避免混淆,但错过了那个。已经更正了。

标签: python class-attributes


【解决方案1】:

使用T().getmemtot() 代替T.getmemtot()。区别在于T 是一个类对象,而T() 是类T 的一个实例。

【讨论】:

  • 我理解 T().getmemtot 有效,因为 getmemtot 是一种对象方法。令我困惑的是为什么在类定义中 T.getmemtot 是可调用的。
  • 你应该使用self 而不是T,而在像MEMTOT=self.getmemtot() 这样的类中工作。它会解决你的困惑。
猜你喜欢
  • 1970-01-01
  • 2017-02-26
  • 2018-12-31
  • 2015-09-25
  • 2013-10-07
  • 1970-01-01
  • 2015-04-11
  • 1970-01-01
  • 2018-07-20
相关资源
最近更新 更多