Skip to main content
 首页 » 编程设计

python之获取 self 的命名属性

2025年05月04日12duanxz

根据我对串联的理解,这段代码应该可以工作:

aList = ["first", "second", "last"] 
for i in aList: 
    print self.i 

我的类定义了绑定(bind) self.first=something 以及 self.second 和 self.last。当我编写 print self.first 时,代码有效,但 print self.i 引发异常。我做错了什么?

请您参考如下方法:

在您的代码中,“i”是一个字符串,您需要这样做:

aList = ["first", "second", "last"] 
for i in aList: 
    print getattr(self, i, None) 

http://docs.python.org/library/functions.html#getattr

getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.