1、多态
同一个方法在不同的类中最终呈现出不同的效果,即为多态。
class Triangle:
def __init__(self,width,height):
self.width = width
self.height = height
def getArea(self):
area=self.width* self.height / 2
return area
class Square:
def __init__(self,size):
self.size = size
def getArea(self): # 同一个方法在不同的类中最终呈现出不同的效果,即为多态
area = self.size * self.size
return area
a=Triangle(5,5)
print(a.getArea())
b=Square(5)
print(b.getArea())
执行效果如下:
2、继承
(1)子类可以继承父类所有的公有属性和公有方法:
class Father:
money = 1000000
def drive(self):
print('I can drive a car!')
class Son(Father):
pass
tom = Father()
print(tom.money)
tom.drive()
print('#'*50)
jerry=Son()
print(jerry.money)
jerry.drive()
执行后:
(2)对于父类的私有属性,子类不可以访问。
(3)对于多继承
多个父类的有相同的某个属性,子类只继承第一个父类的属性。
3、方法重载
子类重写父类的方法:
class Father:
money = 1000000
__money = 9999999
def drive(self):
print('I can drive a car!')
class Son(Father):
def drive(self): #重载父类的方法drive()
print('I can drive a tank!')
Father.drive(self) #在子类中直接调用父类的方法drive()
def pay(self):
print(self.money)
tom = Father()
print(tom.money)
tom.drive()
print('#'*50)
jerry = Son()
jerry.drive()
执行后:
重载运算符
class Mylist: #定义类Mylist
__mylist = []
def __init__(self,*args):
self.mylist = []
for arg in args:
self.__mylist.append(arg)
def __add__(self,x): #定义操作+
for i in range(0,len(self.__mylist)): #依次遍历列表,执行加操作
self.__mylist[i] = self.__mylist[i]+x
return self.__mylist
def __sub__(self,x):
pass
def __mul__(self,x):
pass
def __div__(self,x):
pass
def __mod__(self,x):
pass
def __pow__(self,x):
pass
def __len__(self,x):
pass
def show(self): #显示列表中的数值
print(self.__mylist)
if __name__ == '__main__': #通过name的内置属性
l = Mylist(1,2,3,4,5) #定义一个列表对象
l+10
l.show()
4、模块
从交互解释器导入包,并调用包中的类和方法。如下:
>>> import claMylist
>>> dir(claMylist)
['Mylist', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
>>> import claMylist as cml
>>> ml=cml.Mylist(6,7,8,9,10)
>>> ml
<claMylist.Mylist object at 0x00000263F78D9240>
>>> ml.show() #执行类中的方法show()
[6, 7, 8, 9, 10]
>>> ml+100
[106, 107, 108, 109, 110]
>>> x=ml+100 #将执行+操作后的值存放在x中
>>> x
[206, 207, 208, 209, 210]
>>>