1.封装
封装的意义:
- 将属性和方法放到一起做为一个整体,然后通过实例化对象来处理;
- 隐藏内部实现细节,只需要和对象及其属性和方法交互就可以了;
- 对类的属性和方法增加 访问权限控制。
2.继承
-
什么是继承:
程序中的继承也是一种关系,是两个类之间的关系。既然是两个类之间的关系,就需要确定一下继承顺序,类比现实世界,程序中的被继承者类称为父类或基类,继承者类称为子类或派生类。 - 示例:
class one():
"""类的帮助信息""" # 类的说明
Code # 类体
class two(one):
"""类的帮助信息""" # 类的说明
Code # 类体
class Demo:
@property
def print_value(self):
return 1
class Demo2(Demo): # 将Demo传入Demo2,让Demo2继承Demo的功能(可以使用Demo的功能)
@property
def print_value2(self):
return 2
value = Demo2()
print(value.print_value) # 可以看到继承了Demo后我们就可以直接访问到Demo中的属性了
执行结果:
1
class Fruit:
color = '绿色'
def harvest(self, color):
print(f"水果是:{color}的!")
print("水果已经收获...")
print(f"水果原来是{Fruit.color}的!")
class Apple(Fruit):
color = "红色"
def __init__(self):
print("我是苹果")
class Orange(Fruit):
color = "橙色"
def __init__(self):
print("\n我是橘子")
apple = Apple() # 实例化Apple()类
apple.harvest(apple.color) # 在Apple()中调用harvest方法,并将Apple()的color变量传入
orange = Orange()
orange.harvest(orange.color) # 在Orange()中调用harvest方法,并将Orange()的color变量传入
执行结果:
我是苹果
水果是:红色的!
水果已经收获...
水果原来是绿色的!
我是橘子
水果是:橙色的!
水果已经收获...
水果原来是绿色的!
3.重写
-
什么是重写:
基类(被继承的类)的成员都会被派生类(继承的新类)继承,当基类中的某个方法不完全适用于派生类时,就需要在派生类中重写父类的这个方法。
class Fruit:
color = '绿色'
def harvest(self, color):
print(f"水果是:{color}的!")
print("水果已经收获...")
print(f"水果原来是{Fruit.color}的!")
class Apple(Fruit):
color = "红色"
def __init__(self):
print("我是苹果")
class Orange(Fruit):
color = "橙色"
def __init__(self):
print("\n我是橘子")
def harvest(self, color): # 重写harvest
print(f"橘子是:{color}的!")
print("橘子已经收获...")
print(f"橘子原来是{Fruit.color}的!")
apple = Apple() # 实例化Apple()类
apple.harvest(apple.color) # 在Apple()中调用harvest方法,并将Apple()的color变量传入
orange = Orange()
orange.harvest(orange.color) # 在Orange()中调用harvest方法,并将Orange()的color变量传入
执行结果:
我是苹果
水果是:红色的!
水果已经收获...
水果原来是绿色的!
我是橘子
橘子是:橙色的!
橘子已经收获...
橘子原来是绿色的!
重写之后,如果发现仍然需要父类方法,则可以强制调用父类方法
1.父类名.父类方法()
Animal.init(self)
2.super(子类名,self).父类方法()
super(Cat, self).init()
- super().父类方法()。只在 python3 可用
网友评论