【问题标题】:implemention of "Sum" calss with Dunder in Python在 Python 中用 Dunder 实现“Sum”类
【发布时间】:2022-07-07 07:16:36
【问题描述】:

我需要帮助, 我想在python中实现“链”类,具有以下功能:

>>> Chain(2.5)(2)(2)(2.5) # sum
9
>>> Chain(3)(1.5)(2)(3) # sum
9.5

>>> Chain(64) == 64
True

>>> Chain('Alex')('Smith')('is')('the')('best.') # concat with space
'Alex Smith is the best.'

>>> Chain('abc')('defg') == 'abc defg'
True

在以下情况下抛出异常:

>>> Chain('Alex')(5) # raising exception with the following message
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: invalid operation

>>> Chain(9)([1, 2]) # raising exception with the following message
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: invalid operation
class Chain:
    def __init__(self,n):
        self.Sum = n

    def __call__(self,nums):
        

    def __repr__(self):
        pass

    def __eq__(self,other):
        return type(self) == type(other)

【问题讨论】:

  • 你能用两句话描述如果有人尝试Chain(&lt;some number&gt;)(2)会发生什么。我认为您可能会发现 __call__ 的初始实现很好。
  • 在你有一个适用于数字的__call__ 的初始实现之后,如果提供的输入是字符串而不是数字,你能看到如何处理这种情况吗?尝试实现并在此处发布。如果你这样做了,其他人会加入并帮助你完成它。
  • 感谢您的宝贵时间。我们可以将数字或字符串传递给类,而不是同时传递它们,或者数字数组或字符串数​​组!我搜索了 call 和 Duder,但找不到将一些输入传递给类的示例!实际上我不知道如何编写 callreprequ 函数的代码。

标签: python-3.x class


【解决方案1】:

这应该适用于列表或任何其他具有__iadd__ 方法的对象。我不确定数组中的项目是否都应该是这个分配的同一个对象。否则,您将不得不实施它。

class Chain:
    def __init__(self, n):
        self.sum = n

    def __call__(self, item):
        try:
            if isinstance(item, str):
                self.sum += ' ' + item
            else:
                self.sum += item
        except TypeError:
            raise Exception('invalid operation')
        return self
    
    def __repr__(self):
        return repr(self.sum)

    def __eq__(self, other):
        return type(self.sum) == type(other)

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2020-03-13
    相关资源
    最近更新 更多