多态
类的继承有两层含义:1、改变 2、扩展
多态就是类的两层意义的一个具体的实现机制,即调用不同类的实例对象下的相同方法,会可能有不一样的实现过程
python中的标准类是多态一个很典型的实现。
class Car:
tyre_count = 4
def __init__(self,length,weight,brand):
self.length = length
self.weight = weight
self.brand = brand
def supply(self):
Pass
class Ele_Car(Car):
def supply(self):
print("Ele_Car need electricity")
class Normal_Car(Car):
def supply(self):
print("Normal_Car need oil")
c1 = Ele_Car("3M","1T","tesla")
c2 = Normal_Car("3.5M","1T","BMW")
c1.supply()
c2.supply()
###############
#Ele_Car need electricity
#Normal_Car need oil
多态是继承的一种实现方式,因此其实两者并不可分割,例子中同样调用了supply方法,虽然同样的继承但经过了改写,因此实现方式不同,这就像一个类有许多不同的形态。
封装
封装顾名思义是封和装,类和函数一样,其中一个作用就是减少代码重用,因此class即是使用代码块进行封装。而类还有一个作用,是当调用类时,其中的细节调用者是看不见的,并且类的定义者可以设定私有属性,防止属性在类之外进行访问。
私有属性
- 使用_进行开头,如_arry;这种方式是python约定好的一种私有属性的定义,并非绝对不可访问。但当使用“from M import”时,不会将以一个下划线开头的对象引入。
- 使用__爽下划线开头,如__myarry;这种方式使用一般的访问方式是无法访问,必须使用
_类名__myarry
进行访问
class Car:
_tyre_count = 4
__cartype = "turbo"
def __init__(self,length,weight,brand):
self.length = length
self.weight = weight
self.brand = brand
def supply(self):
Pass
print(Car._tyre_count) #结果为4
print(Car.__dict__) # '_Car__cartype': 'turbo' 其中私有属性被改写成这种模式
print(Car.__cartype) #因此直接如此调用,会报错提示无法找到该属性