Python 对于某些方法而不是其他方法,如何忽略
对不起,我不太确定如何更准确地写标题 我有一个带有Python 对于某些方法而不是其他方法,如何忽略,python,jupyter,Python,Jupyter,对不起,我不太确定如何更准确地写标题 我有一个带有\uu repr\uu()的类来报告类的一些关键属性 我的大多数方法都返回self,因此我可以菊花链方法。e、 g.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 {s
\uu repr\uu()
的类来报告类的一些关键属性
我的大多数方法都返回self,因此我可以菊花链方法。e、 g.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__
\uuuu repr\uuuu
在Jupyter中工作得非常好,因为它可以通过执行ac
来为我提供一些关键属性的报告。但是,我有一个play()
方法来播放音频,它也会返回self,我绝对不希望打印执行,因为有时我可能需要快速多次调用此方法
那么,有没有一种方法可以让在我所有的方法中返回self
,而不是在返回时调用\uuuuu repr\uuu
非常感谢如果将结果分配给某个变量,则交互式输入不会调用
\uuuuu repr\uuu
我会:
_ = ac.play()
使用一个匿名的\uu
变量来明确它是一次性的,这还保留了交互式解释器功能,它隐式地将任何函数结果存储在\u
中
就速度而言,是的,它更快,因为没有调用\uu repr\uu
,而且无论发生什么情况,\u
都会被分配
ac.play()
-分号可防止IPython/Jupyter显示输出,或将其分配给Out
或
从err,分配给某个对象
u=ac.play()
?好主意,它会以任何方式影响速度吗?我不明白为什么在play
方法中需要返回self
。@wjandrea有时可以方便地“链接”方法,如ac.plus(n=4).play().debug_info()
等ac.play()
-分号阻止ipython/jupyter
显示输出,或将其分配给Out
或
。我喜欢这样,因为如果您不做任何事情,交互式解释器通常会将结果分配给
。所以在行为上真的没有什么不同。是的,我只是在我的回答中加了一句:)这也是一个很好的方法。谢谢