I am wondering if it is possible to write count(vanilla) instead of vanilla.count() ? It is similar to len(list) but I want to do len(myclass). Is it possible to implement like this on my user define class? Below just a dummy class I wrote to ask this question. Thank you.
class IceCream():
# Flavor is a string
# Toppings is a list of strings
def __init__(self, flavor, toppings, ):
self.name = flavor
self.toppings = toppings
# Return the number of toppings
def count(self):
return len(self.toppings)
def __str__(self):
return "{0} flavor ice cream".format(self.name)
vanillaToppings = ['chocolate chips', 'fudge', 'penuts']
vanilla = IceCream('Vanilla', vanillaToppings)
print(vanilla, 'with', vanilla.count(), 'kind of toppings!')
# Is it possible? If so, how do I do it?
# print(vanilla, 'with', len(vanilla), 'kind of toppings!')
How about utilizing one of python’s special methods:
__len__?I would guess that the meaning of count and length are somewhat interchangeable in this case, so why not use something familiar?