我有一个对象 a 它有一个属性 b 值为 c
那么我 a.b 这样就能得到 c
现在我有个变量 d = 'b'
我怎么才能通过变量 d 拿到对象 a 中的 b 的值
举个例子,如果在 php 中能这样 $a->$d
那么我 a.b 这样就能得到 c
现在我有个变量 d = 'b'
我怎么才能通过变量 d 拿到对象 a 中的 b 的值
举个例子,如果在 php 中能这样 $a->$d
1
raptium Sep 3, 2012 a.__dict__[d]
a.__getattr__(d) 或者 a.__getattribute__(d) 也許更好 |
2
yuelang85 Sep 3, 2012 getattr(a, d)
|
3
tunetoystory OP |
4
013231 Sep 3, 2012
你也可以實現類的__getitem__, __setitem__方法, 然後就可以像Javascript那樣用'[]'運算符訪問屬性了.
|
5
tunetoystory OP @013231 嗯,这个比较高端
|