我想知道是否可以写count(vanilla)
而不是vanilla.count()
?它类似于len(list)
但我想做len(myclass)
。是否可以在我的用户定义类上实现这样的功能?下面只是我写的一个虚拟课程来问这个问题。谢谢你。
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!')