Ugur
Ugur

Reputation: 2014

Implicitly call method when instance name is called

In an instance, is there a way I can call a method implicitly when I am calling just the instance name?

So for example if I have this

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()

Is that possible?


Background

In the Panda's source code I can see this in a docstring:

    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.

In the second paragraph it says:

Styler has defined a `_repr_html_` to automatically render itself

Source: Github: Pandas

Upvotes: 0

Views: 470

Answers (3)

lvc
lvc

Reputation: 35059

Instead of _render_html, call it __call__. This will be called by mc(). The step further than this - dropping the brackets in the calling code - is not possible, but you can come close if you make _render_html a property like so:

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

Then you can do mc.html, without the brackets, to call that function.

Upvotes: 1

Relandom
Relandom

Reputation: 1039

You can try to assign this function to some variable:

mc = MyClass._render_html_(MyClass(some_fancy_html))

Then you when you call mc it will call class method. Of course, you can always pass already existing class object as a self:

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

Then typing method will execute same what would do: mc._render_html_()

Upvotes: 0

I don't think you can do that. I'd rather overload the parentheses operator, just like 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

Upvotes: 3

Related Questions