簡體   English   中英

如何從類中返回一個方法?

[英]How to return a method from a class?

我有一個類Netflix和一個方法find_popular_category 但是我無法獲得返回我正在尋找的單詞的方法。

class Netflix:
    def find_popular_category(self):
        path = os.path.abspath('../data/netflix.csv')
        with open(path, encoding= 'utf-8-sig') as file:
            open_file = csv.reader(file)
            next(file)

            lst = []
            for x in open_file:
                cate = x[10]
                lst.append(cate)

            spt = [category for word in lst for category in word.split(",")]  # splits every word in the string "list"

            word_count = Counter(spt)  # counts the categories
            most = word_count.most_common(1)  # gets most categories
            print(most)
            return most[0][0]


netflix = Netflix()
netflix.find_popular_category()
print(netflix)

輸出:

[(' International Movies', 1842)]  # This is because of print(most).
<__main__.Netflix object at 0x000001C254E711C8>  
# Why doesn't it return only International Movies? 

看起來您只是在打印對象的實例。 我會將 netflix.find_popular_category() 分配給一個變量並打印出來。 例如

popularCategory = netflix.find_popular_category()

print(popularCategory)

您正在嘗試打印Netflix對象的實例。 但是你需要打印函數的結果:

print(netflix.find_popular_category())

代替:

print(netflix)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM