【发布时间】: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