假设我正在尝试编写一个在所有方面都像元组的类,除了一个:当您使用print
它时,大于10的任何值都将替换为10。通常,我会通过拥有一个继承元组但更改__str__
magic方法的类来做到这一点。但是,我不知道元组的__str__
魔术方法是如何编写的,因此我不确定如何访问每个单独的元素以检查它是否大于10才能进行打印。
是否有任何解决方案(如果相关的话,这些元组将只有两个字段)?
class sampleClass(tuple):
def __str__(self):
return "({0}, {1})".format(min(elem1IsomehowGet, 10), min(elem2IsomehowGet, 10))
>>> x = sampleClass((3, 15))
>>> print x
(3, 10)
>>> x[1]
15
我认为这是您要寻找的:
class sampleClass:
def __init__(self, tup):
self.tup = tup
def __str__(self): #To print it
return str(tuple([item if item <= 10 else 10 for item in self.tup])) #List comprehension to replace x > 10 with 10, then convert to a tuple, then surround with quotes so __str__ accepts it
def __getitem__(self, ind): #To access by index e.g. x[1], x[-1] etc.
return self.tup[ind]
>>> from sampleClass import sampleClass as sc
>>> x = sc((3, 15))
>>> x[1]
15
>>> print x
(3, 10)
>>>
注意:我用替换了所有大于10的值'H'
,这是您在问题中所写的内容,但是,在您的问题中,
您用10替换了它。
注意:JK,您编辑了问题
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句