[python] Python iterating through object attributes

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

This question is related to python python-2.7 object for-loop

The answer is


Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

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

for attr, value in vars(k).items():
    print(attr, '=', value)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?