如何从类定义中的列表理解中访问其他类variables? 以下Python 2中的工作,但在Python 3中失败: class Foo: x = 5 y = [x for i in range(1)] Python 3.2给出的错误: NameError: global name 'x' is not defined 尝试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'], # … ]] 在这个例子中, […]
我想了解内置的函数property如何工作。 令我困扰的是,这个property也可以作为装饰器使用,但是当它作为一个内置函数使用时,它仅仅需要参数,而不能当作装饰器使用。 这个例子来自文档 : class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") property的参数是getx , setx , delx和一个文档string。 在下面的代码中, property被用作装饰器。 它的对象是x函数,但在上面的代码中,参数中没有对象函数的地方。 class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' […]
我不明白如何遍历字典或在python中设置是由“任意”的顺序。 我的意思是,这是一种编程语言,所以语言中的所有内容都必须100%确定,正确吗? Python必须有一些决定select字典或集合的哪一部分的algorithm,第一,第二等等。 我错过了什么?