Python 迭代对象属性

102 投票
3 回答
234914 浏览
提问于 2025-04-18 16:10

我该如何在Python中遍历一个对象的属性呢?

我有一个类:

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"])

现在我可以通过这样来获取我的信息:

k = Twitt()
k.twitter_lookup("51.5033630,-0.1276250", "1mi")
print k.names

我想要做的是像这样在一个循环中遍历这些属性:

for item in k:
   print item.names

3 个回答

9

在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 "")

输出结果:

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

你可以使用Python的一个常用方法,叫做 vars()

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

更新:

在Python 3中,你应该使用 items() 而不是 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)

这段代码会打印:

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

撰写回答