Reputation: 11
I have tried converting key to a string or reassigning key to another variable. Key will return an attribute within sample, but key is not being seen as sample_name...
for key in samples[1].__dict__:
print(key)
for row in samples:
print(row.key)
Output:
sample_name
Traceback (most recent call last):
print(row.key)
AttributeError: 'sample' object has no attribute 'key'
Upvotes: 0
Views: 829
Reputation: 787
Try to see if the following code helps you:
for key in samples[1].__dict__:
print(key)
for row in samples:
print getattr(row, key)
Upvotes: 0
Reputation: 46
Well, i've spent a little time to figure out what you want.
samples
is a list. Each object in list samples
is a class instance with few attribute. And you want to output their value of each attribute?
If I'm right you may try
for each in samples:
for key in each.__dict__:
try:
print(each.key)
except AttributeError, Argument:
print('AttributeError')
print(Argument)
However I don't think it's a good idea to use __dict__
. Give more info about you problem might help us provide more useful suggestions.
Upvotes: 0
Reputation: 9010
When you do row.key
, you are trying to look up the 'key'
attribute on row
. This is equivalent to doing getattr(row, 'key')
. Since row
has no 'key'
attribute, this produces an error. To dynamically look up an attribute when you have a string for the attribute name, use getattr(row, key)
and since key = 'sample_name'
, this is equivalent to getattr(row, 'sample_name')
. Notice the lack of quotes around key
in the first usage.
Upvotes: 1