Override Methods With Same Name In Python Programming
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 w
Solution 1:
Discussed here:
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:
classA(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.
Post a Comment for "Override Methods With Same Name In Python Programming"