实例名称被调用时的隐式调用方法

时间:2019-05-17 09:38:18

标签: python

在一个实例中,当我仅调用实例名称时,是否可以隐式调用方法?

例如,如果我有这个

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

3 个答案:

答案 0 :(得分:3)

我认为您无法做到。我宁愿重载括号运算符,就像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

答案 1 :(得分:1)

将其命名为_render_html,而不是__call__mc()将调用此方法。不能执行进一步的操作-将调用方括号放在调用代码中-但如果您将_render_html设置为如下属性,则可以接近:

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

然后您可以mc.html(不带括号)来调用该函数。

答案 2 :(得分:0)

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

mc = MyClass._render_html_(MyClass(some_fancy_html))

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

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

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

相关问题