built-in functions as class attributes

M

Mark Dickinson

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:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_hex() takes exactly 1 argument (2 given)
[36412 refs]

Anyone know what the precise rules that lead to this
behaviour are, or where they're documented?

Surprised'ly yours,

Mark
 
P

Peter Otten

Mark said:
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:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_hex() takes exactly 1 argument (2 given)
[36412 refs]

Anyone know what the precise rules that lead to this
behaviour are, or where they're documented?

To work properly as a method a callable needs a __get__() method
implementing the binding mechanism. Functions written in C generally don't
have that.
.... def __call__(self, *args):
.... print "called with", args
........ a = A()
....called with ()

Now let's turn A into a descriptor:
.... print inst, cls
.... if inst is not None:
.... def bound(*args):
.... self(inst, *args)
.... return bound
.... return self
....<__main__.B object at 0x2ae49971b890> <class '__main__.B'>
called with (<__main__.B object at 0x2ae49971b890>,)

I don't know if there is something official, I google for

http://users.rcn.com/python/download/Descriptor.htm

or "descrintro" every time I need a refresher.

Peter
 
A

alex23

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:

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:
'0x3039'

Hope this helps.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top