简体   繁体   中英

How to return a method from a class?

I have a class Netflix and a method find_popular_category . However I can't get the method to return the word I'm looking for.

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)

Output:

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

It looks like you are just printing the instance of the object. I would assign netflix.find_popular_category() to a variable and print that instead. For example

popularCategory = netflix.find_popular_category()

print(popularCategory)

You are trying to print the instance of the Netflix object. But you need to print the result of the function:

print(netflix.find_popular_category())

Instead of:

print(netflix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM