开发者

How should I rethink objects/object orientation here?

开发者 https://www.devze.com 2023-04-01 08:16 出处:网络
I\'m (mostly trying to learn python and json, but also) trying to periodically pull and format a list of trending topics off of twitter. I cobbled this together skimming a lot of different tutorials.

I'm (mostly trying to learn python and json, but also) trying to periodically pull and format a list of trending topics off of twitter. I cobbled this together skimming a lot of different tutorials. It serves my purposes -- prints the HTML I need to stdout, but I'm wondering if I could have thought about objects differently or structured it better. Assist?

class trend:
        #these are the fields that Twitter provides, so they make up one trend.
        def __init__(self, query, name, promoted_content, events, url):
                self.query = query
                self.name = name
                self.promoted_content = promoted_content
                self.events = events
                self.url = url 

        def listitem(self):
                print "\t <li><a href=\"%s\">%s</a></li>\n" %(self.url, self.name)

class trending:
        def __init__(self,api_url,title):
                self.api_url = api_url
                self.title = title

        def get_trending(self):
                import simplejson as json
                import urllib2

                trends_all = json.loads(urllib2.urlopen(self.api_url).read())
                # test print
                # print trends_all[0]['trends']
                print "<p>%s</p> \n <ol>" % self.title

            开发者_如何学编程    #I'm initializing an array, though I don't actually use it. That's next.
                trends = []
                for x in trends_all[0]['trends']:
                    thistrend = trend(x['query'], x['name'], x['promoted_content'], x['events'], x['url'])
                    thistrend.listitem()
                    trends.append(thistrend) 
                print "</ol>\n"
                return trends

usa = trending("http://api.twitter.com/1/trends/23424977.json","Trending nationally")
usa.get_trending()

feedback?


In your example, I don't see why trending needs to be a clas at all, since it only has one function. This could be written with get_trending as a standalone function, which takes the api_url and title as arguments.

0

精彩评论

暂无评论...
验证码 换一张
取 消