类
对类的理解
类抽象出有相同属性或行为的对象 例如生物学中的贝类,哺乳类
创建类
class Car(self,brand,price):
def __init__(self):
self.brand = brand
self.price = price
def car_information(self):
print(f"my car is {brand}")
print(f"it cost {price}")
对象
类的实例化被称为对象
#创建对象
my_car=Car(Audi,100k)
#调用类中的函数
my_car.car_information()
继承和组合
继承
子类继承父类,可以表达出父类中的内容
交互模式
- 子类动作等同于父类动作
- 子类动作完全覆盖父类动作
- 子类动作部分覆盖父类动作
隐式继承
"""创建一个类作为父类"""
class Parent:
def implicit(self):
print("PARENT implicit()")
"""创建另一个类作为子类"""
class Child(Parent):
pass
dad=Parent()
son=Child()
dad.implicit()
son.implicit()
"""运行结果"""
PARENT implicit()
PARENT implicit()
显式覆盖
要实现对父类的显式覆盖,只需在子类中重新定义一个父类中的函数
"""创建一个类作为父类"""
class Parent:
def implicit(self):
print("PARENT implicit()")
"""创建另一个类作为子类"""
class Child(Parent):
def implicit(self):
print("CHILD implicit()")
dad=Parent()
son=Child()
dad.implicit()
son.implicit()
"""运行结果"""
PARENT implicit()
CHILD implicit()
运行前或运行后进行替换
class Parent(object):
def altered(self):
print("PARENT implicit()")
class Child(Parent):
def altered(self):
print("CHILD , BEFORE PARENT altered()")
super(Child , self).altered()
print("CHILD , AFTER PARENT altered()")
dad = Parent()
son = Child()
dad.intered()
son.intered()
"""运行结果"""
PARENT implicit()
CHILD , BEFORE PARENT altered()
PARENT altered()
CHILD , AFTER PARENT altered()
组合
"""创建类"""
class Other(object):
def overside(self):
print("Other overside()")
def implicit(self):
print("Other implicit()")
def altered(self):
print("Other altrered()")
class Child(object):
def __init__(self):
self.other = Other()
def implicit(self):
self.other.implicit()
def overside(self):
print("CHILD overside()")
def altered(self):
print("CHILD , AFTER OTHER altrered()")
self.other.altered()
print("CHILD , AFTER OTHER altered()")
"""创建实例"""
son = Child()
son.implicit()
son.overside()
son.alered()
"""运行结果"""
Other implicit()
CHILD overside()
CHILD , AFTER OTHER altrered()
Other altrered()
CHILD , AFTER OTHER altered()