【问题标题】:How should I rethink objects/object orientation here?我应该如何在这里重新考虑对象/面向对象?
【发布时间】:2011-08-31 20:38:40
【问题描述】:

我(主要是尝试学习 python 和 json,但也)尝试定期从 twitter 中提取和格式化热门话题列表。我把这个拼凑起来浏览了很多不同的教程。它符合我的目的——将我需要的 HTML 打印到标准输出,但我想知道我是否可以以不同的方式考虑对象或更好地构建它。辅助?

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()

反馈?

【问题讨论】:

    标签: python json twitter simplejson


    【解决方案1】:

    在您的示例中,我不明白为什么趋势需要成为一个类,因为它只有一个功能。这可以用get_trending 作为独立函数编写,它以 api_url 和标题作为参数。

    【讨论】:

    • 嗯......我希望能够稍微扩展它。我刚刚将“get_trending”分解为 get_trending(以获取趋势)、li_trending(将它们作为列表项打印)、array_trending(将它们推入数组)和 list_trending(以纯文本形式列出)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多