我已经通过了许多链接,但是使用
python理解多态的最简单的方法是什么…有任何简单的例子.从我的理解多态是一个概念,其中一个对象可以采取不止一次的形式..任何人都可以让我知道任何简单的例子而不是复杂的
http://swaroopch.com/notes/python_en-object_oriented_programming/
http://www.tutorialspoint.com/python/python_classes_objects.htm
最佳答案 这看起来像一个简单的例子:
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#Example
从维基百科文章复制的示例:
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Dog('Lassie')]
for animal in animals:
print(animal.name + ': ' + animal.talk())
# prints the following:
# Missy: Meow!
# Lassie: Woof! Woof!
BTW python使用duck typing来实现多态性,如果你想了解更多信息,可以搜索该短语.