同一种事物的多种形态
# 多态:同一种事物的多种形态
class Animal:
def run(self):
pass
class People(Animal):
def run(self):
print("people is walking")
class Pig(Animal):
def run(self):
print("pig is walking")
class Dog(Animal):
def run(self):
print("dog is walking")
多态性
在不考虑实例类型的情况下,直接使用实例。多态性分为静态多态性和动态多态性
好处:1、增加了程序的灵活性(以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal))
2、增加了程序的可扩展性(通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal))
# 多态:同一种事物的多种形态
class Animal:
def talk(self):
pass
class People(Animal):
def talk(self):
print("say hello")
class Cat(Animal):
def talk(self):
print("mew mew")
class Dog(Animal):
def talk(self):
print("woof woof")
# 多态性:指的是可以在不考虑对象类型的情况下而直接使用对象
people = People()
cat = Cat()
dog = Dog()
# 动态多态性
# people.talk()
# cat.talk()
# dog.talk()
def func(animal):
animal.talk()
func(people)
func(dog)
func(cat)
鸭子类型
Python崇尚鸭子类型,即‘如果看起来像、叫声像而且走起路来像鸭子,那么它就是鸭子’
class File:
def read(self):
pass
def write(self):
pass
class Disk:
def read(self):
print("disk read")
def write(self):
print("disk write")
class Text:
def read(self):
print("text read")
def write(self):
print("text write")
disk = Disk()
text = Text()
disk.read()
disk.write()
text.read()
text.write()
类似于
# 序列类型:列表list,元组tuple,字符串str
l = list([1,2,3])
t = tuple(("a","b"))
s = str("hello")
print(l.__len__())
print(t.__len__())
print(s.__len__())
def len(obj):
return obj.__len__()
print(len(l))
print(len(t))