python functions

Question:

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.

Asked By: dragonfly

||

Answers:

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
Answered By: Amber

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.

Answered By: Roman Bodnarchuk

HW 3.12) Implement function points() that takes as input four numbers x1, y1, x2, y2 that
are the coordinates of two points (x1; y1) and (x2; y2) in the plane. Your function should
compute:
• The slope of the line going through the points, unless the line is vertical
• The distance between the two points
Your function should print the computed slope and distance in the following format. If the
line is vertical, the value of the slope should be string ‘infinity’. Note: Make sure you
convert the slope and distance values to a string before printing them.

points(0, 0, 1, 1)
The slope is 1.0 and the distance is 1.41421356237
points(0, 0, 0, 1)
The slope is infinity and the distance is 1.0

Answered By: dheeraj shathragna
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.