-4

Possible Duplicate:
How do I use method overloading in Python?

I am new to Python programming, and I like to write multiple methods with the same name, but why only the method which is called recently get printed?

Code is below:

class A:
    def mymethod(self):
        print 'first method'
    def mymethod(self):
        print 'second method'
ob = A()
ob.mymethod()

With the output as second method.

What is the mechanism behind this Python method calling? Can I call two methods of the same name at the same time?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1335578
  • 2,587
  • 2
  • 18
  • 15
  • 2
    You can't have multiple methods with the same name. We just answered that in the other question. If that's not what you're trying to do, please describe your question more clearly. – agf Apr 18 '12 at 05:24
  • 4
    Wow Mukthyar. Something you should know... These SO gurus read every post even while on the toilet. You cant sneak a duplicate question by anyone here. – jdi Apr 18 '12 at 05:42
  • @agf, this seems worse than the first question - here the methods don't even have different signatures – John La Rooy Apr 18 '12 at 05:44
  • Hi jdi duplicate question also written by me only ,we can't judge worse and good,at learning stage of programming. these question will clear doubt in programming. – user1335578 Apr 19 '12 at 05:12

1 Answers1

2

Discussed here:

Python function overloading

In Python, functions are looked up by name. The types of the arguments are not part of the name, and are not declared anywhere. The function can be called with arguments of any type.

If you write your function using "duck typing" you can usually make one function do all the different jobs you need it to do. Arguments with default values are also often used, to allow for calling the function with a different number of arguments.

Here is a simple example:

class A(object):
    def __init__(self, value=0.0):
        self.value = float(value)

a = A()  # a.value == 0.0
b = A(2)  # b.value == 2.0
c = A('3')  # c.value = 3.0
d = A(None)  # raises TypeError because None does not convert to float

In this example, we want a float value. But we don't test the type of the argument; we just coerce it to float, and if it works, we are happy. If the type is wrong, Python will raise an exception for us.

Community
  • 1
  • 1
steveha
  • 74,789
  • 21
  • 92
  • 117