我正在使用 Python 2.7(谷歌应用引擎)
学习Python
了,弄明白了语言是如何利用继承来实现多态的。
INHERITANCE
-基于多态性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()
我的问题是:Python 是否具有松散耦合的多态性,即使用interface
而不是inheritance
. 例如,在 Java 中,没有祖先关系的类可以实现相同的接口。请参阅以下示例中的HouseDog
和。PetRock
INTERFACE
-基于多态性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
}
问题:
再说一遍:python 是否有一种面向对象的方式来实现多态性而不使用继承?