obtaining named attributes of self
according to my understanding of concatenation this code should work:
aList = ["first", "second", "last"]
for i in aList:
print self.i
My class defines the bindings self.first=something
as well as self.second
and self.last
. When I write print self.fi开发者_如何学Crst
the code works but print self.i
raises an exception. What am I doing wrong?
In your code, "i" is a string, you need to do that:
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.
You confuse first
- a member of your class - with "first"
- a string variable which happens to hold a content similar to your member.
Use getattr
if you want to convert from the string to the real field
精彩评论