一、多态
Python变量并不需要声明类型,同一个变量可以在不同的时间引用不同的对象,当一个变量在调用同一个方法,可以呈现出多种行为,而具体呈现出哪种行为由该变量引用的对象来决定,这就是多态。
先看一下以下例子:
class Dog: def behavior(self,skill): print (‘小狗会%s!‘%skill) class Cat: def behavior(self,skill): print (‘小猫会%s!‘%skill) class Host: def pet(self,met,*arg): print (‘小明的宠物有特殊技能,‘,end = ‘‘) met.behavior(self,*arg) H = Host() H.pet(Dog,‘唱‘) # 打印 小明的宠物有特殊技能,小狗会唱! H.pet(Cat,‘跳‘) # 打印 小明的宠物有特殊技能,小猫会跳!
上面的例子中,当涉及Host类的pet()方法时,该方法传入的参数对象只需要具有behavior()方法就可以了,怎样的行为特征完全取决于对象本身。
二、检查类型
Python提供了两个函数来检查类型,issubclass()和isinstance()。
先查看一下issubclass()函数的用法,
>>> help(issubclass) Help on built-in function issubclass in module builtins: issubclass(cls, class_or_tuple, /) Return whether ‘cls‘ is a derived from another class or is the same class. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) or ...`` etc.
可以看到,该函数用于判断cls参数是否是class_or_tuple参数的子类或者是同一个类。
例:
class Dog: def behavior(self): print (‘小狗会唱!‘) class Cat: def skill(self): print (‘小猫会跳!‘) class Host(Dog): def pet(self): print (‘小明有一只宠物!‘) print (issubclass(Cat,Cat)) # 同一个类,打印 True print (issubclass(Dog,Host)) # Dog类是Host类的父类,所以打印 False print (issubclass(Dog,Cat)) # Dog类不是Cat类的子类,所以打印 False print (issubclass(Host,Dog)) # Host类是Dog类的子类,所以打印 True
再看一下isinstance()函数的用法,
>>> help(isinstance) Help on built-in function isinstance in module builtins: isinstance(obj, class_or_tuple, /) Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) or ...`` etc.
isinstance()函数用于判断一个对象是否是一个已知的类型,obj参数类型和class_or_tuple参数类型相同,则返回Ture,否则False。
例:
a = ‘1111‘ print (type(a)) # <class ‘str‘> print (isinstance(a,str)) # 参数a类型不是str,返回 True print (isinstance(a,int)) # 参数a类型不是int,返回 False
原文地址:https://www.cnblogs.com/mingmingming/p/11221352.html
时间: 2024-10-08 22:16:26