Python遍历对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25150955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:48:48  来源:igfitidea点击:

Python iterating through object attributes

pythonpython-2.7objectfor-loop

提问by Zach Johnson

How do I iterate over an object's attributes in Python?

如何在 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 循环中的属性,如下所示:

for item in k:
   print item.names

采纳答案by levi

UPDATED

更新

For python 3, you should use items()instead of iteritems()

对于 python 3,你应该使用items()而不是iteritems()

PYTHON 2

蟒蛇2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

蟒蛇3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

这将打印

'names', [a list with names]
'tweet', [a list with tweet]

回答by Eric Leschinski

Iterate over an objects attributes in python:

在 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:

回答by arekolek

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

您可以使用标准的 Python 习语vars()

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