【发布时间】: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(<some number>)(2)会发生什么。我认为您可能会发现__call__的初始实现很好。 -
在你有一个适用于数字的
__call__的初始实现之后,如果提供的输入是字符串而不是数字,你能看到如何处理这种情况吗?尝试实现并在此处发布。如果你这样做了,其他人会加入并帮助你完成它。 -
感谢您的宝贵时间。我们可以将数字或字符串传递给类,而不是同时传递它们,或者数字数组或字符串数组!我搜索了 call 和 Duder,但找不到将一些输入传递给类的示例!实际上我不知道如何编写 call 、repr 和 equ 函数的代码。
标签: python-3.x class