9

Pythonでgetattr関数とsetattr関数を使用してリスト内のアイテムにアクセス/割り当てようとしています。残念ながら、リスト名とともにリストインデックス内の場所を渡す方法はないようです。
これがいくつかのサンプルコードでの私の試みのいくつかです:

class Lists (object):
  def __init__(self):
    self.thelist = [0,0,0]

Ls = Lists()

# trying this only gives 't' as the second argument.  Python error results.
# Interesting that you can slice a string to in the getattr/setattr functions
# Here one could access 'thelist' with with [0:7]
print getattr(Ls, 'thelist'[0])


# tried these two as well to no avail.  
# No error message ensues but the list isn't altered. 
# Instead a new variable is created Ls.'' - printed them out to show they now exist.
setattr(Lists, 'thelist[0]', 3)
setattr(Lists, 'thelist\[0\]', 3)
print Ls.thelist
print getattr(Ls, 'thelist[0]')
print getattr(Ls, 'thelist\[0\]')

また、attr関数の2番目の引数では、この関数で文字列と整数を連結できないことに注意してください。

乾杯

4

3 に答える 3

9
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]

のようなことができるようにしたい場合は、組み込み関数getattr(Ls, 'thelist[0]')をオーバーライドまたは使用する必要があります。__getattr__eval

于 2011-08-01T04:44:50.357 に答える
5

あなたができること:

l = getattr(Ls, 'thelist')
l[0] = 2  # for example
l.append("bar")
l is getattr(Ls, 'thelist')  # True
# so, no need to setattr, Ls.thelist is l and will thus be changed by ops on l

getattr(Ls, 'thelist')でアクセスできる同じリストへの参照を提供しますLs.thelist

于 2011-08-01T03:14:33.013 に答える
3

あなたが発見したように、__getattr__このようには機能しません。本当にリストのインデックス付けを使用したい場合は、 and を使用__getitem____setitem__、 and は忘れてgetattr()くださいsetattr()。このようなもの:

class Lists (object):

    def __init__(self):
        self.thelist = [0,0,0]

    def __getitem__(self, index):
        return self.thelist[index]

    def __setitem__(self, index, value):
        self.thelist[index] = value

    def __repr__(self):
        return repr(self.thelist)

Ls = Lists()
print Ls
print Ls[1]
Ls[2] = 9
print Ls
print Ls[2]
于 2011-08-19T01:04:15.280 に答える