【问题标题】:Implicitly call method when instance name is called调用实例名称时隐式调用方法
【发布时间】:2019-05-17 09:38:17
【问题描述】:

在一个实例中,当我只调用实例名称时,有没有一种方法可以隐式调用方法?

例如,如果我有这个

class MyClass:
    def __init__(self, html):
       self.html = html
    def _render_html_(self):
       # omitted
       pass

>>> some_fancy_html = """(omitted)"""
>>> mc = MyClass(some_fancy_html)

## So instead of
>>> mc._render_html_()

## I would like to call
>>> mc
### to implicitly call the method _render_html()

这可能吗?


背景

在 Panda 的源代码中,我可以在文档字符串中看到这一点:

    Notes
    -----
    Most styling will be done by passing style functions into
    ``Styler.apply`` or ``Styler.applymap``. Style functions should
    return values with strings containing CSS ``'attr: value'`` that will
    be applied to the indicated cells.

    If using in the Jupyter notebook, Styler has defined a ``_repr_html_``
    to automatically render itself. Otherwise call Styler.render to get
    the generated HTML.

第二段说:

Styler has defined a `_repr_html_` to automatically render itself

来源: Github: Pandas

【问题讨论】:

  • init 你可以让它调用 __render_html(self)?
  • mc() 将执行类的构造函数。
  • 不,不会的,构造函数会在你做mc = MyClass(...时被调用。请参阅下面我的回答,了解当您致电 mc() 时会发生什么。

标签: python


【解决方案1】:

我认为你做不到。我宁愿重载括号运算符,就像it's explained here

>>> class MyClass:
...     def __init__(self, html):
...             self.html = html
...     def __call__(self):
...             print(self.html)
... 
>>> mc = MyClass("Hello, world")
>>> mc
<__main__.MyClass instance at 0x7f3a27a29bd8>
>>> mc()
Hello, world

【讨论】:

    【解决方案2】:

    _render_html 改为__call__。这将由mc() 调用。比这更进一步的步骤 - 在调用代码中删除括号 - 是不可能的,但如果你将 _render_html 设置为这样的属性,你可以接近:

    class MyClass:
        @property
         def html(self):
             pass
    

    然后你可以使用mc.html,不带括号,调用该函数。

    【讨论】:

    • 我非常喜欢您的第二个解决方案。但最初的问题是关于省略任何属性/方法调用。因此我接受了 Jose 的解决方案。
    【解决方案3】:

    您可以尝试将此函数分配给某个变量:

    mc = MyClass._render_html_(MyClass(some_fancy_html))
    

    然后你当你调用 mc 时它会调用类方法。 当然,您始终可以将已经存在的类对象作为 self 传递:

    some_fancy_html = """(omitted)"""
    mc = MyClass(some_fancy_html)
    method = MyClass._render_html_(mc)
    

    然后输入method 将执行相同的操作:mc._render_html_()

    【讨论】:

    • 这通常是一个很好的方法,但重要的是要提到它不一定符合 OP 想要的。特别是如果mc 跟踪该方法所依赖的任何状态,则调用该方法一次并保持返回值不会反映对该状态的任何更改。
    • 感谢您提及这一点!实际上很难匹配 OP 想要的,因为 _render_html_ 函数是空的。无论如何,我很高兴你提到了这一点。
    猜你喜欢
    • 2015-01-17
    • 2020-12-19
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2013-10-04
    • 2018-06-06
    • 2014-10-12
    • 2016-07-29
    相关资源
    最近更新 更多