[英]how to ignore __repr__() for certain method but not others
sorry I am not quite sure how to put the title more accurately. 抱歉,我不太确定如何更准确地放置标题。
I have a class with __repr__()
to report the some key attributes of class. 我有一个带有
__repr__()
的类来报告该类的一些关键属性。
Most of my methods return self, so that I can daisy-chain methods. 我的大多数方法都返回self,因此我可以采用菊花链方法。 eg
a.m1().m2()...
例如
a.m1().m2()...
class Myclass:
def __init__(self):
self.a = 1
self.b = "hello"
def __repr__(self):
msg = f"Myclass: a = {self.a}, b is {self.b}."
return msg
def plus(self, n):
self.a += n
return self
def concat(self, s):
self.b += s
return self
def play(self):
# play audio here
return self
ac = Myclass()
ac.plus(n=4) # Ok i would like to see __repr__ output
ac.play() # no I dont want to see __repr__
The __repr__
works great in Jupyter as it can give me a report on some key attributes by just executing ac
. __repr__
在Jupyter中非常有效,因为只需执行ac
就可以给我一些关键属性的报告。 However, I have a play()
method to play the audio, which also return self, and I absolutely do not want the print to execute as sometime I might need to call this method multiple times quickly. 但是,我有一个
play()
方法来播放音频,该方法也会返回self,我绝对不希望执行打印,因为有时我可能需要快速多次调用此方法。
So is there a way to have return self
in all my methods, but not call __repr__
on return? 那么有没有办法让我所有的方法都
return self
,但是不返回__repr__
呢?
Many thanks 非常感谢
if you assign the result to some variable, the interactive input doesn't call __repr__
. 如果将结果分配给某个变量,则交互式输入不会调用
__repr__
。
I'd do: 我会做:
_ = ac.play()
using an anonymous _
variable to make it clear that it's throwaway, which also keeps the interactive interpreter feature which stores any function result in _
implicitly. 使用匿名
_
变量来明确说明它是一次性的,这还保留了将所有函数结果隐式存储在_
的交互式解释器功能。
In terms of speed, yes, it's faster since __repr__
isn't called, and _
would be assigned no matter what. 在速度方面,是的,因为没有调用
__repr__
,所以速度更快,并且无论如何都会分配_
。
ac.play();
- the semicolon keeps IPython/Jupyter from displaying the output, or assigning it toOut
or_
.-分号可防止IPython / Jupyter显示输出,或将其分配给
Out
或_
。
from hpaulj's comment 来自hpaulj的评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.