In many programming languages, types are immutable and compatibility is enforced. This is not generally true in Python, but still there are operations that require specific types. Indexing into a string or tuple must be done using something much like an integer, and not by using a float. Now that classes can be used to build what amounts to new types, more attention should be paid to the things a type should offer and the requirements this puts on a programmer. The fewer restrictions the better, and this is a principle of duck typing as well.
It should not really matter what the exact type of the object is that is being manipulated, only that it possesses the properties that are needed. In a very simple case, consider the classes point and triangle that were discussed at the beginning of this chapter. It was proposed that both could have a draw() method that would create a graphical representation of these on the screen, and both have a move() method, as well. We write a function that moves a triangle away from a point and draws them both:
def moveaway (a, b)
dx = a.getx()-b.getx()
dy = a.gety()-d.gety()
a.move (dx/10, dy/10)
b.move (-dx/10, -dy/10)
Which of the parameters, a or b, is the triangle, and which is the point? It does not matter. Both classes have the methods needed by this function, namely getx(), gety(), and move(). Because of this, the calls are symmetrical, and both of the following are the same:
moveaway (a, b)
moveaway (b, a)
A class that possesses these three methods can be passed to moveaway(), and a result will be calculated without error. The essence of duck typing is that, so long as an object offers the service needed (i.e., a method of the correct name and parameter set) to another function or method, then the call is acceptable. There is a way to tell whether the class instance a has a getx() method: the built-in function hasattr().
if hasattr (v1, “getx”):
x = v1.getx()
The first argument is a class instance and the second is the name of the method that is needed, as a string. It returns True if the method exists.
(The name duck typing comes from the old saying that “if something walks like a duck and quacks like a duck, then it is a duck.” As long as a class offers the things asked for, then it can be used in that context.)
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.