面向对象之多态,property

多态:
同一种事物有多种状态
多态性:
在不考虑对象具体类型的前提下直接调用对象下的方法
静态多态性和动态多态性
静态多态性:都可以进行+操作
动态多态性:不考虑对象具体类型调用方法
多态的好处:
①增加了程序的灵活性
②增加了程序的可扩展性
多态的用法
为了规范子类的方法
定了抽象类,抽象类无需实现具体的方法,但继承了抽象类的子类必须实现抽象类的方法,否则报错
import abc

class Foo(metaclass = abc.ABCMeta):
def run(self):
pass

class Person(Foo):
@abc.abstractmethod
def run(self):
pass

property 将类中方法伪装成属性
class Foo:
@property
def AAA(self):
print('get的时候运行我啊')

@AAA.setter
def AAA(self,value):
    print('set的时候运行我啊')

@AAA.deleter
def AAA(self):
    print('delete的时候运行我啊')

只有在属性AAA定义property后才能定义AAA.setter,AAA.deleter

f1=Foo()
f1.AAA
f1.AAA='aaa'
del f1.AAA

property的原理,是一个非数据描述符,修改了get函数,调用属性时返回的是该属性名对应的绑定方法(参数为实例名)

class Lazyproperty:
def init(self,func):
self.func=func
def get(self, instance, owner):
print('这是我们自己定制的静态属性,r1.area实际是要执行r1.area()')
if instance is None:
return self
return self.func(instance) #此时你应该明白,到底是谁在为你做自动传递self的事情

class Room:
def init(self,name,width,length):
self.name=name
self.width=width
self.length=length

@Lazyproperty #area=Lazyproperty(area) 相当于定义了一个类属性,即描述符
def area(self):
    return self.width * self.length

r1=Room('alex',1,1)
print(r1.area)

猜你喜欢

转载自www.cnblogs.com/robert-zhou/p/10145007.html