Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python iterating through object attributes [duplicate]

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 
like image 593
Zach Johnson Avatar asked Aug 06 '14 01:08

Zach Johnson


People also ask

How do you iterate over an object in Python?

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.

What is __ Getattribute __ in Python?

__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.


2 Answers

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] 
like image 166
levi Avatar answered Oct 14 '22 08:10

levi


You can use the standard Python idiom, vars():

for attr, value in vars(k).items():     print(attr, '=', value) 
like image 45
arekolek Avatar answered Oct 14 '22 09:10

arekolek