from collections import namedtuple
Gaga = namedtuple('Gaga', ['id', 'subject', 'recipient'])
g = Gaga(id=1, subject='hello', recipient='Janitor')
Run Code Online (Sandbox Code Playgroud)
我希望能够获得此列表(保留属性的顺序):
[1, 'hello', 'Janitor']
Run Code Online (Sandbox Code Playgroud)
我可以手动创建这个列表,但必须有一个更简单的方法.我试过了:
g._asdict().values()
Run Code Online (Sandbox Code Playgroud)
但属性不是我想要的顺序.
我试图利用Python @property来修改类属性的类属性List.大多数在线示例假设@property修饰的属性是一个奇异值,而不是可以通过setter扩展的列表.
稍微澄清一下问题:我不只是想为属性s分配一个值(int列表的值),而是需要修改它(将新的int附加到当前列表).
我的目的是期望:
c = C()
c.s # [1,2,3] is the default value when instance c initiated.
c.s(5)
c.s # [1,2,3,5]
Run Code Online (Sandbox Code Playgroud)
给出C如下的实施:
class C:
def __init__(self):
self._s = [1,2,3]
@property
def s(self):
return self._s
@s.setter
def s(self, val):
self._s.append(val)
Run Code Online (Sandbox Code Playgroud)
如果我这样做c.s(5),我会得到的
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-99-767d6971e8f3> in <module>()
----> 1 c.s(5)
TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)
我已经阅读了最相关的帖子: 列表上的Python属性 和 带有列表的Python装饰属性setter
但两者都不适合我的情况:
__setitem__可以修改列表的元素,但我想扩展列表.
对于我当前的任务,不能使用全局属性.
在这方面,什么是最好的解决方案?(或者我不应该从一开始就期望@property在可变数据结构上?)谢谢!
------ -----编辑
@Samuel Dion-Girardeau建议
子类列表并定义其 …
我有两个属性,其中包含列表.每当此列表中的任何项目发生更改时,我希望其他列表自行更新.这包括声明obj.myProp[3]=5.现在,这个语句调用getter函数获取整个列表,从列表中获取第三个项目,并将其设置为5. myProp列表已更改,但第二个列表永远不会更新.
class Grid(object):
def __init__(self,width=0,height=0):
# Make self._rows a multi dimensional array
# with it's size width * height
self._rows=[[None] * height for i in xrange(width)]
# Make `self._columns` a multi dimensional array
# with it's size height * width
self._columns=[[None] * width for i in xrange(height)]
@property
def rows(self):
# Getting the rows of the array
return self._rows
@rows.setter
def rows(self, value):
# When the rows are changed, the columns are updated
self._rows=value
self._columns=self._flip(value)
@property …Run Code Online (Sandbox Code Playgroud)