built-in functions as class attributes

alex23 wuwei23 at gmail.com
Tue Dec 9 05:31:38 CET 2008


On Dec 8, 8:46 pm, Mark Dickinson <dicki... at gmail.com> wrote:
> Here's a curiosity:  after
>
> def my_hex(x):
>     return hex(x)
>
> one might expect hex and my_hex to be interchangeable
> in most situations.  But (with both Python 2.x and 3.x)
> I get:
>
> >>> def my_hex(x): return hex(x)
> ...
> >>> class T(object): f = hex
> ...
> >>> class T2(object): f = my_hex
> ...
> >>> T().f(12345)
> '0x3039'
> >>> T2().f(12345)
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: my_hex() takes exactly 1 argument (2 given)
> [36412 refs]

You're attaching 'my_hex' as a method to T2, which by default will
automatically try to pass in the instance to 'f' when called. This is
why you explicitly declare 'self' as the first argument for methods.
And as Peter's post points out, this behaviour doesn't happen with
built-in functions.

However, when attaching 'my_hex', you can explicitly state that you
don't want this behaviour by using the 'staticmethod' decorator:

>>> def my_hex(x): return hex(x)
...
>>> class T2(object): f = staticmethod(my_hex)
...
>>> T2().f(12345)
'0x3039'

Hope this helps.



More information about the Python-list mailing list