module with __call__ defined is not callable?
limodou
limodou at gmail.com
Tue Feb 7 23:10:29 EST 2006
On 2/8/06, Delaney, Timothy (Tim) <tdelaney at avaya.com> wrote:
> limodou wrote:
>
> > On 2/8/06, adam johnson <adam.sven.johnson at gmail.com> wrote:
> >> Thanks for you answer.
> >>
> >> I was under the impression that you could tack methods onto an
> >> object at any time, your example almost works with old style classes
> >> and would with a function instead of a method.
>
> In fact it will work if you change the A.hello to self.hello ...
>
> class A:
>
> def __init__(self):
> self.__call__ = self.hello
>
> def hello (self):
> print 'Hello, world!'
>
> a = A()
> a()
>
> Hello, world!
>
> >> So now all I need to know is why now with new style classes the
> >> special functions need to be defined on the class instead of
> >> attached to the instance at any time.
>
> http://users.rcn.com/python/download/Descriptor.htm
>
> > don't need do like above!
> >
> > >>> class A:
> > ... def __init__(self):
> > ... A.__call__ = A.hello
> > ... def hello(self):
> > ... print "Hello, world!"
> >
> > >>> a = A()
> > >>> a()
> > Hello, world!
> >
> > You should review the bound method and unbound method.
>
> This has nothing to do with it - in the above example, you are setting
> the *class* attribute of a user-defined class (which allows setting
> additional attributes) - which therefore makes instances callable.
>
Of course I know that.
> Compare the equivalent for the current module:
>
> import sys
>
> def hello (self):
> print 'Hello, world!'
>
> m = sys.modules[__name__]
> mc = type(m)
> mc.__call__ = hello
>
> Traceback (most recent call last):
> File "D:\Python\modules\testclasscall.py", line 7, in ?
> mc.__call__ = hello
> TypeError: can't set attributes of built-in/extension type 'module'
>
The exception is right, some special method cannot be replace for some
built-in type(new-style class). I just don't suggest adding __call__()
to a module, I don't know why does he need this. Because I think the
module normally works like a namespace.
--
I like python!
My Blog: http://www.donews.net/limodou
NewEdit Maillist: http://groups.google.com/group/NewEdit
More information about the Python-list
mailing list