Unexpected behavior with class and instance variables...
aleaxit at yahoo.com
Wed Jul 11 09:06:12 CEST 2001
"tracy s. ruggles" <trace at reinventnow.com> wrote in message
news:B77159A3.390B%trace at reinventnow.com...
> I'm trying to build a wrapper for any given function and noticed some odd
> behavior with using class variables instead of instance variables.
Yep. Specifically (3.2 in the Language Reference manual):
User-defined method objects are created in two ways: when getting
an attribute of a class that is a user-defined function object, or
when getting an attribute of a class instance that is a user-defined
function object defined by the class of the instance.
In other words: when you access a class attribute (whether from
the class object, or from an instance of the class) and the
class attribute is a user-defined function, then what you get
is *NOT* a function-object: you get a method-object instead.
No such magic transformation occurs when you access an instance
attribute stricto sensu (one held in the instance's __dict__,
as opposed to one the instance gets from its __class__). No
such magic transformation occurs for ANY other type of class
attribute EXCEPT "user-defined function-objects". One common
workaround is thus to wrap a user-defined function into some
other kind of callable. See for example
for a bit more discussion. The key idea there is:
def __init__(self, anycallable):
self.__call__ = anycallable
and use Callable(myfunction) rather than the bare myfunction
to set your class attributes.
Alternatively, you can use the im_func attribute of a method
object to get back the underlying function object.
More information about the Python-list