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

标签 python class function

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

相关文章:

python - pyqt 非模态对话框总是模态的

class - 为什么 Scala 包对象中的类不受欢迎?

php - 函数内部的静态变量不能保存对单例的引用

matlab - 从数据创建传递函数并将其应用于音频信号

python - 在 Django 中添加 ManyToManyField 时出错

Python JSON 抓取 - 如何处理缺失值?

python - 使用 Pandas 组合/合并 2 个不同的 Excel 文件/工作表

c++ - 如何从自己类的成员函数中访问公共(public)变量? (C++)

html - 什么是 HTML 中的类?

swift - “Functions are a first-class type” swift ?