How do I iterate over an object's attributes in Python?
I have a class:
class Twitt: def __init__(self): self.usernames = [] self.names = [] self.tweet = [] self.imageurl = [] def twitter_lookup(self, coordinents, radius): cheese = [] twitter = Twitter(auth=auth) coordinents = coordinents + "," + radius print coordinents query = twitter.search.tweets(q="", geocode=coordinents, rpp=10) for result in query["statuses"]: self.usernames.append(result["user"]["screen_name"]) self.names.append(result['user']["name"]) self.tweet.append(h.unescape(result["text"])) self.imageurl.append(result['user']["profile_image_url_https"])
Now I can get my info by doing this:
k = Twitt() k.twitter_lookup("51.5033630,-0.1276250", "1mi") print k.names
I want to be able to do is iterate over the attributes in a for loop like so:
for item in k: print item.names
Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. next ( __next__ in Python 3) The next method returns the next value for the iterable.
__getattribute__This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.
UPDATED
For python 3, you should use items()
instead of iteritems()
PYTHON 2
for attr, value in k.__dict__.iteritems(): print attr, value
PYTHON 3
for attr, value in k.__dict__.items(): print(attr, value)
This will print
'names', [a list with names] 'tweet', [a list with tweet]
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items(): print(attr, '=', value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With