Python:多态,静态方法和类方法
多继承的弊端:容易引发冲突,增加代码设计复杂度#****#
多态:


class Animal(object):
def shoot(self):
print("shoot")
class Cat(Animal):
def shoot(self):
print("momo")
class Dog(Animal):
def shoot(self):
print("wawa")
cat=Cat()
cat.shoot()
dog=Dog()
dog.shoot()
输出结果为:
momo
wawa
多态性:一种调用方式,能够有不同的执行结果:
class Animal(object):
def shoot(self):
print("shoot")
class Cat(Animal):
def shoot(self):
print("momo")
class Dog(Animal):
def shoot(self):
print("wawa")
#多态性:定义一个统一的接口,一个接口多种实现
def test(obj):#函数传入不同的对象执行不同对象的方法
obj.shoot()
animal=Animal()
cat=Cat()
dog=Dog( )
test(animal)
test(cat)
test(dog)
输出结果为:
shoot
momo
wawa
静态方法:
使用语法糖装饰器@staticmethod来进行修饰,静态方法没有self,cls参数的限制
不需要访问实例属性和类属性,如果要访问类属性,通过类名,类属性名访问,不能访问实例属性
与类无关,可以转换成函数使用:
class Animal(object):
@staticmethod
def shoot(name):
print(f"{name}shoot")
#静态方法既可以使用对象访问,也可以使用类访问
Animal.shoot('lihailu')#调用方法时传参数
pe=Animal()
pe.shoot('liahilu')
应用场景:取消不必要的参数传递有利于减少不必要的内存占用和性能消耗
类方法:使用装饰器@classmethod来标识为类方法,第一个参数必须是类对象,一般的话是以cls作为第一个参数:
class Animal(object):
@classmethod
def shoot(cls):
print(cls)#cls代表类对象本身,类本质上就是一个对象
print("shoot")
pe=Animal()
pe.shoot()
输出结果为:
<class '__main__.Animal'>
shoot
类方法内部可以访问类属性,或者调用其他的类方法,可以通过cls.类属性名访问类属性,不能访问实例属性:
class Animal(object):
name='lihailu'
@classmethod
def shoot(cls):
print(cls)
print("shoot")
print(cls.name)#Animal.name
pe=Animal()
pe.shoot()
应用场景:当方法中需要使用到类对象(如访问私有类属性等),定义类方法
类方法一般配合类属性使用
class Animal(object):
name='lihailu'#类属性,对象拥有的
def __init__(self):
self.age=18;#实例属性,对象私有的
def play(self):#实例方法
#在实例方法中访问类属性
print(f"{Animal.name} is playing")
pe=Animal()
pe.play()
class Animal(object):
name='lihailu'#类属性,对象拥有的
def __init__(self):
self.age=18;#实例属性,对象私有的
# def play(self):#实例方法
# #在实例方法中访问类属性
# print(f"{Animal.name} is playing")
# print(self.age)
@staticmethod
def introduce():
print(f"I am {Animal.name}")#能访问到类属性但没意义
pe=Animal()
pe.introduce()
class Animal(object):
name='lihailu'#类属性,对象拥有的
def __init__(self):
self.age=18;#实例属性,对象私有的
# def play(self):#实例方法
# #在实例方法中访问类属性
# print(f"{Animal.name} is playing")
# print(self.age)
@classmethod
def introduce(cls):
print(f"I am {cls.name}")#代表类对象本身
pe=Animal()
pe.introduce()
总结:类属性是公共的,所有方法都能够访问到,静态方法不需要访问类属性(静态方法和类与对象没有关联),实例属性是私有的,只有实例方法内部能够访问到
