dragonfly
dragonfly

Reputation: 33

python functions

class Test:
       def func():
           print('func')
test1 = Test()
test2 = Test()

test1.func()  #TypeError: fun1() takes no arguments (1 given)
test2.newfunc = Test.func
test2.newfunc()#It goes well

# update part
def foo(self):
    pass
Test.foo = foo
test1.foo # it is bound method
test2.foo = foo
test2.foo # it is function
# end 

Is there any difference between the two ways ? Thanks.

# update part
def foo(self):
    pass
Test.foo = foo
test1.foo # it is bound method
test2.foo = foo
test2.foo # it is function
# end 

Note that what's important is that the retrieval should take place in class instead of instance.

Upvotes: 2

Views: 274

Answers (2)

Roman Bodnarchuk
Roman Bodnarchuk

Reputation: 29717

A bit of investigation:

>>> test1.func
<bound method Test.func of <__main__.Test instance at 0x800f211b8>>
>>> Test.func
<unbound method Test.func>

Then user-defined bound method (test1.func in our case) is called, this call is actually performed as Test.func(test1) - class instance is always passed as first argument.

See much more on this topic in Python Data model.


Edit

Output above is from Python 2.6. Since Test.func() works for you, I assume that you are using Python 3. In this case output will be the next:

>>> test1.func
<bound method Test.func of <__main__.Test object at 0xb747624c>>
>>> Test.func
<function func at 0xb74719ec>

As you see, Test.func is a simple function, so no 'magic' will be added while calling it.

Upvotes: 2

Amber
Amber

Reputation: 526573

Methods of a class that are called on an instance of the class are passed the instance reference as an argument automatically. Thus, they're usually declared with a self argument:

class Test:
       def func(self):
           print('func')

test1 = Test()
test1.func() # self = test1

Upvotes: 6

Related Questions