相关疑难解决方法(0)

从类定义中的列表推导中访问类变量

如何从类定义中的列表推导中访问其他类变量?以下适用于Python 2但在Python 3中失败:

class Foo:
    x = 5
    y = [x for i in range(1)]
Run Code Online (Sandbox Code Playgroud)

Python 3.2给出了错误:

NameError: global name 'x' is not defined
Run Code Online (Sandbox Code Playgroud)

尝试Foo.x也不起作用.有关如何在Python 3中执行此操作的任何想法?

一个稍微复杂的激励示例:

from collections import namedtuple
class StateDatabase:
    State = namedtuple('State', ['name', 'capital'])
    db = [State(*args) for args in [
        ['Alabama', 'Montgomery'],
        ['Alaska', 'Juneau'],
        # ...
    ]]
Run Code Online (Sandbox Code Playgroud)

在这个例子中,apply()本来是一个不错的解决方法,但它遗憾地从Python 3中删除.

python scope list-comprehension python-3.x python-internals

152
推荐指数
3
解决办法
2万
查看次数

在类体中调用类staticmethod?

当我尝试在类的主体内使用静态方法,并使用内置staticmethod函数作为装饰器定义静态方法时,如下所示:

class Klass(object):

    @staticmethod  # use as decorator
    def _stat_func():
        return 42

    _ANS = _stat_func()  # call the staticmethod

    def method(self):
        ret = Klass._stat_func() + Klass._ANS
        return ret
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Traceback (most recent call last):<br>
  File "call_staticmethod.py", line 1, in <module>
    class Klass(object): 
  File "call_staticmethod.py", line 7, in Klass
    _ANS = _stat_func() 
  TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)

我理解为什么会发生这种情况(描述符绑定),并且可以通过_stat_func()在上次使用后手动转换为static方法来解决它,如下所示:

class Klass(object):

    def _stat_func():
        return 42

    _ANS = _stat_func()  # use the non-staticmethod version

    _stat_func = staticmethod(_stat_func) …
Run Code Online (Sandbox Code Playgroud)

python static-methods decorator

134
推荐指数
5
解决办法
9万
查看次数

从类变量引用静态方法

我知道有这样的情况是有线的但不知怎的,我有它:

class foo
  #static method
  @staticmethod
  def test():
    pass

  # class variable
  c = {'name' : <i want to reference test method here.>}
Run Code Online (Sandbox Code Playgroud)

它的方法是什么?

仅供记录:

我认为这应该被视为python最差的做法.如果有的话,使用静态方法并不是真正的pythoish方式......

python static-methods class-variables

2
推荐指数
1
解决办法
455
查看次数