need a simple way to add meta information/class to a python list/tuple variable?

℡╲_俬逩灬. 提交于 2019-12-10 19:34:16

问题


All,

I want simple meta information to be enclosed on an list object, see below code.

>>> a = []
>>> a.foo = 100
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'list' object has no attribute 'foo'
>>> setattr(a,"foo",100)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'list' object has no attribute 'foo'
>>> dir(a)
...
 '__setattr__',
 '__setitem__',
...

my quesions are

  1. why I can not use setattr() for variable "a" as the list should have 'setattr' function already?

  2. is there a simple way to attach meta info to list/tuple variable instead of overload 'setattr' or embedded that list into a dict?

thanks!


回答1:


The base types defined in C cannot have arbitrary attributes added; you must derive a Python type from them in order to change this.

>>> class MyList(list):
...   pass
... 
>>> m = MyList((1, 2, 3))
>>> len(m)
3
>>> m.foo = 42
>>> m.foo
42



回答2:


  1. it does have setattr. it does not have attribute 'foo', as the message says.
  2. yes, subclass it, e.g.

class mylist(list):
 pass

l = mylist()
l.foo = 'bar'


来源:https://stackoverflow.com/questions/5240567/need-a-simple-way-to-add-meta-information-class-to-a-python-list-tuple-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!