简体   繁体   English

如何为某些方法而不是其他方法忽略__repr __()

[英]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 to Out or _ . -分号可防止IPython / Jupyter显示输出,或将其分配给Out_

from hpaulj's comment 来自hpaulj的评论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM