Reputation: 6003
I am using Python 2.7 (google app engine)
Learning Python
, I have figured out how the language uses inheritance to achieve polymorphism.
INHERITANCE
-BASED POLYMORPHISM IN PYTHON
:
class pet:
number_of_legs = None
age = None
def sleep(self):
print "zzz"
def count_legs(self):
print "I have %s legs." % self.number_of_legs
return self.number_of_legs
class dog(pet):
def bark(self):
print "woof"
doug = dog()
doug.number_of_legs = 5;
print "Doug has %s legs." % doug.count_legs()
doug.bark()
My question is this: Does Python have loosely coupled polymorphism, i.e. using interface
instead of inheritance
. For example, in Java, classes with no ancestral relationships may implement the same interface. See HouseDog
and PetRock
in the following example.
INTERFACE
-BASED POLYMORPHISM IN JAVA
:
class Animal{
int legs;
double weight;
public int getLegs(){return this.legs;}
public double getWeight(){return this.weight}
}
interface Pet{
public int getNumberOfDresses();
public int getNumberOfToys();
}
class HouseDog extends Animal implements Pet{
//... implementation here
}
class PetRock implements Pet{
//a rock and a dog don't really have much in common.
//But both can be treated as pets
}
QUESTION:
Again: Does python have an object-oriented way to achieve polymorphism without using inheritance?
Upvotes: 0
Views: 2225
Reputation: 36551
Yes, they call it Duck Typing. There's no need to formally implement an interface. Java-style interfaces don't exist because Python has multiple inheritance, so if you want to define the interface, you just use a regular class as the supertype. But, generally, people avoid creating completely abstract base classes, and avail themselves of duck typing.
For your example, one would just omit the Pet
interface, but let HouseDog
and PetRock
both have getNumberOfDresses
and getNumberOfToys
methods. In polymorphic situations, Python checks for the existence of the methods, only when they are called, instead of checking the types at compile-time (which doesn't exist) or load-time. The big advantage is in letting you rapidly prototype without worry about the formalisms while your implementation isn't yet complete.
If you do want formal type-checking, you can get it in a number of ways, but none is officially sanctioned.
Upvotes: 6