Override methods with the same name in python programming

Possible duplicate:
How to use method overloading in Python?

I am new to python programming, I like to write several methods with the same name, but why only the method that is called recently is printed? code as below

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

with o / p as second method

please tell me which mechanism of this python method calls. I can call two methods of the same name at the same time.

Thanks Mukthyar

-5
python
source share
1 answer

We discuss here:

Python function overload

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

If you write your function using duck printing, you can usually make one function to do all the tasks you need. Arguments with default values ​​are also often used to allow calling a 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 need a float value. But we do not check the type of argument; we just force him to swim, and if that works, we are happy. If the type is wrong, Python will throw an exception for us.

+1
source share

All Articles