Re: instance has no __call__ method

Discussion in 'Python' started by Steve Holden, Dec 11, 2010.

  1. Steve Holden

    Steve Holden Guest

    On 12/10/2010 5:20 AM, frank cui wrote:
    > Hi all,
    >
    > I'm a novice learner of python and get caught in the following trouble
    > and hope experienced users can help me solve it:)
    >
    > Code:
    > -----------------------------------------------------------------------
    > $ cat Muffle_ZeroDivision.py
    > #!/usr/bin/env python
    >
    > class MuffledCalculator:
    > muffled = False
    > def clac(self,expr):
    > try:
    > return eval(expr)
    > except:
    > if self.muffled:
    > print 'Division by zero is illegal'
    > else:
    > raise
    > --------------------------------------------------------------------------
    >
    > $ python
    > Python 2.7 (r27:82500, Sep 16 2010, 18:03:06)
    > [GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
    > Type "help", "copyright", "credits" or "license" for more information.
    >>>> import Muffle_ZeroDivision
    >>>> calc = Muffle_ZeroDivision.MuffledCalculator()
    >>>> calc = ('10/2')
    >>>> calc = Muffle_ZeroDivision.MuffledCalculator()
    >>>> calc('10/2')

    > Traceback (most recent call last):
    > File "<stdin>", line 1, in <module>
    > AttributeError: MuffledCalculator instance has no __call__ method
    >
    > ----------------------------------------------------------------------------
    >
    > There is an AttributeError that this instance doesn't have the __call__
    > method, so how to add this kind of method to my instance?
    >
    > Thanks a lot in advance.
    >
    > Regards
    > Frank.Cui
    >

    Try renaming your .calc() method to .__call__(). That way the method
    will be called when you perform a function call on an instance.

    regards
    Steve
    --
    Steve Holden +1 571 484 6266 +1 800 494 3119
    PyCon 2011 Atlanta March 9-17 http://us.pycon.org/
    See Python Video! http://python.mirocommunity.org/
    Holden Web LLC http://www.holdenweb.com/
    Steve Holden, Dec 11, 2010
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. chenyu
    Replies:
    1
    Views:
    295
  2. Robert Ferrell

    Redefining __call__ in an instance

    Robert Ferrell, Jan 15, 2004, in forum: Python
    Replies:
    5
    Views:
    365
    John Roth
    Jan 21, 2004
  3. Robert Brewer

    RE: Redefining __call__ in an instance

    Robert Brewer, Jan 16, 2004, in forum: Python
    Replies:
    1
    Views:
    432
    Jason Mobarak
    Jan 16, 2004
  4. Ksenia Marasanova
    Replies:
    2
    Views:
    326
    Ksenia Marasanova
    Sep 9, 2005
  5. Marco
    Replies:
    1
    Views:
    176
    Ian Kelly
    Nov 20, 2012
Loading...

Share This Page