我想知道是否可以寫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