如何从类定义中的列表推导中访问其他类变量?以下适用于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中删除.
当我尝试在类的主体内使用静态方法,并使用内置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) 我知道有这样的情况是有线的但不知怎的,我有它:
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方式......