Python - 在类方法和属性上混淆

时间:2015-03-27 21:52:19

标签: python class

我目前无法尝试编写练习计划。

from bs4 import BeautifulSoup
import urllib

class Query:

    def __init__(self, feed_id, max_results):
        self.feed_id = feed_id
        self.max_results = max_results
        self.content_data = []  
        self.num_likes = []
        self.num_dislikes = []
        self.stats = []
        self.view_count = []

    def getQuery(self):
        web_obj = urllib.urlopen("http://gdata.youtube.com/feeds/api/standardfeeds/%s?max- results=%s&time=today" % (self.feed_id, self.max_results))
        file = open('youtubequery.txt', 'w+')
        file.write(str(web_obj))
        for i in web_obj:
            file.write(i)
        with open("youtubequery.txt", "r") as myfile:
            file_2=myfile.read()
            soup = BeautifulSoup(file_2)

        for link in soup.find_all("content"):
            self.content_data.append(str(link.get("src")))
        print self.content_data
        for stat in soup.find_all("yt:statistics"):
            self.stats.append(str(stat.get("favoritecount")))
        print self.stats
        for views in soup.find_all("yt:statistics"):
            self.view_count.append(str(views.get("viewcount")))
        print self.view_count
        for numlikes in soup.find_all("yt:rating"):
            self.num_likes.append(str(numlikes.get("numlikes")))
        print self.num_likes
        for numdislikes in soup.find_all("yt:rating"):
            self.num_dislikes.append(str(numdislikes.get("numdislikes")))
        print self.num_dislikes

    # def __str__(self):
    #    print self.content_data
    #                           This doesn't work


#Class Video:(Query):

   #def __init__(self):
    #   pass

stuff = Query("top_rated", "5")
print stuff.__str__()

我需要的是__str__()方法从我的班级打印数据,而不是getQuery()方法。我对如何使用__str__()感到困惑。

我还想将属性self.content_dataself.stats传递给视频类。我会继承从QueryVideo的所有内容吗? 感谢您的帮助......我是新手使用Classes所以我可以使用一些帮助。

1 个答案:

答案 0 :(得分:0)

__str____repr__方法必须返回一个字符串,所以您需要做的就是:

def __str__(self):
    return str(self.content_data)
  

我会继承从查询到视频的所有内容吗?

是的,所有公共属性和方法都将被继承。