gpt4 book ai didi

python - 我可以切换这个函数 vanilla.count()

转载 作者:太空宇宙 更新时间:2023-11-04 09:15:26 24 4
gpt4 key购买 nike

我想知道是否可以编写 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!')

最佳答案

如何利用 python 的 special methods 之一? : __len__

Called to implement the built-in function len(). Should return the length of the object, an integer >= 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!')

我猜想 countlength 的意思在这种情况下可以互换,所以为什么不用熟悉的东西呢?

关于python - 我可以切换这个函数 vanilla.count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10023013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com