我想知道是否可以写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!')
答案 0 :(得分:2)
如何使用python的special methods之一:__len__
?
调用实现内置函数len()。应返回对象的长度,整数> = 0。
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 __len__(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', len(vanilla), 'kind of toppings!')
我想在这种情况下, count 和 length 的含义在某种程度上是可以互换的,那么为什么不使用熟悉的东西?
答案 1 :(得分:2)
len()
是一个获取传递长度的函数。所以你可以编写一个传递一个对象的函数count()
,并对它进行计数(但是你定义了“count”)。
len()
函数在实例上调用特殊方法__len__()
。您可以为count()
定义类似的界面,以便那些想要使用您的函数的人可以在自己的类上定义一个特殊方法供count()
使用。 (不要用两个前导下划线和两个尾随下划线来命名它;这是为Python保留的。一个前导和尾随下划线将是我的建议。)然后你只需在你自己的对象上实现该接口。
这样的事情:
def count(obj):
return obj._count_()
class IceCream(object):
def _count_(self):
return len(self.toppings)
miku建议您在课堂上实施__len__()
并使用len()
。这也是一个很好的解决方案,但它可能会产生其他容器或迭代器方法可用的印象。
答案 2 :(得分:1)
请参阅http://docs.python.org/reference/datamodel.html,了解您可以实施的魔术方法。你想要的是def __len__(self): return len(self.toppings)
然后您可以使用len(yourinstance)
来获取该函数的返回值。
你不能为count(yourinstance)
执行此操作;至少不是一个干净的方式。
非干净的方式是:
def count(instance):
return instance.count()
我没有使用__count__
因为__*__
被认为是为__len__
这样的官方python事物保留的。但无论如何,请忘记上面几行水平线以下的所有内容 - 你真的不想这样做。使用__len__
即可。