module with __call__ defined is not callable?
Delaney, Timothy (Tim)
tdelaney at avaya.com
Tue Feb 7 22:54:16 EST 2006
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.
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'
Tim Delaney
More information about the Python-list
mailing list