我想知道是否可以写count(vanilla)
而不是vanilla.count()
?它类似于len(list)
,但我想做len(myclass)
。是否有可能在我的用户定义类上这样实现?下面是我写的一个虚拟课堂来问这个问题。谢谢。我可以切换此功能vanilla.count()
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!')
是的,我注意到'__len__'的作品,但是如果我想做'__count__'呢?在那种情况下,无论如何,我可以把它放在我的课堂上,而不是在课堂外单独分开? – George 2012-04-05 05:25:15
号'count()'不是像'len()'这样的内置函数。 – Amber 2012-04-05 05:25:43
但是我们可以重载所有的内置函数吗? (通过重载,我想我应该说:我们可以将它们定义为我们认为合适的?) – George 2012-04-05 05:29:48