This question already has an answer here:
这个问题在这里已有答案:
- Iterate over object attributes in python 7 answers
- 迭代python 7答案中的对象属性
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
3 个解决方案
#1
53
UPDATED
更新
For python 3, you should use items()
instead of iteritems()
对于python 3,你应该使用items()而不是iteritems()
PYTHON 2
PYTHON 2
for attr, value in k.__dict__.iteritems():
print attr, value
PYTHON 3
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]
#2
16
You can use the standard Python idiom, vars()
:
您可以使用标准Python惯用语,vars():
for attr, value in vars(k).items():
print(attr, '=', value)
#3
8
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:
#1
53
UPDATED
更新
For python 3, you should use items()
instead of iteritems()
对于python 3,你应该使用items()而不是iteritems()
PYTHON 2
PYTHON 2
for attr, value in k.__dict__.iteritems():
print attr, value
PYTHON 3
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]
#2
16
You can use the standard Python idiom, vars()
:
您可以使用标准Python惯用语,vars():
for attr, value in vars(k).items():
print(attr, '=', value)
#3
8
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: