python类的继承与多态
- 通过继承得到基本类型的功能
- 被继承的被叫做基类或者父类,继承的叫做子类
- 子类(继承者)有着父类(被继承着)的所有方法 以及类属性
- 父类(被继承着)不具备子类(继承者)的属性和方法
- 如果子类继承了父类的方法 子类也有着同样的方法 那么 子类的方法生效,可以利用此对继承过来的方法进行重写(类的多态)
示例
class Parent:#默认继承object类
name = "father"
age = 56
moneys = "1000w"
def __init__(self) -> None:
pass
# self.name = "father"
# self.age = 56
# self.moneys = "1000w"
def behaver(self):
print("{}老了走不动了".format(self.age))
def money(self):
print("我继承了爸爸的money{}".format(self.moneys))
class children(Parent):#继承父类,参数可以是多个父类 就是多重继承
def __init__(self) -> None:
self.name = "child"
self.age = 26
def behaver(self):
print("{}年轻健步如飞".format(self.age))
def money2(self):
print("我没有money,")
# parent1 = Parent()
# parent1.behaver()
child1 = children()#实例化child类
child1.money() #继承了父类的money
#类的多态
child1.behaver()#26年轻健步如飞 因为方法名和属性名一致 所以重新了父类的方法
super()函数
- 在子类的构造函数中 执行父类的构造函数 并传参
- super(子类名称,self).父类的方法,并且可以传递参数
class Parent:
def __init__(self, money) -> None:
self.name = "father2"
self.age = 54
self.moneys = money
def money(self):
print("我继承了爸爸的money{}".format(self.moneys))
class children(Parent):
def __init__(self) -> None:
super(children, self).__init__("5000w") # 实例化的时候执行父类的构造函数
self.name = "child"
self.age = 26
def money2(self):
print("我没有money,")
child1 = children()
child1.money() # 继承了爸爸的money5000w
类中的高阶函数
函数名 | 用法 | 返回值 |
---|---|---|
_str_() | 一般返回该类的描述信息(例子如下) | 一段描述信息 |
_getattr_(self,key) | key调用任意一个不存在的属性名(key)会返回提示信息 | 可以是信息 也可以不返回 |
_setattr_(self,key,value) | 拦截当前类中不存在的属性与值,可以进行一些处理 | 可有可无 |
_call_ | 给类的实例对象传参会触发 | 可有可无 |
__str__
class text:
def __str__(self) -> str:
return "这是一个测试类"
print(text()) #这是一个测试类
__getattr__
class text2:
def __getattr__(self, key) -> Any:
print("当前的这个变量:{}不存在".format(__name))
a = text2()
a.rte #当前的这个变量:rte不存在
__setattr__
class text3:
def __init__(self, name) -> None:
self.name = name
#拦截当前类中不存在的属性与值,如果不存在 就添加
def __setattr__(self, key: str, value: Any) -> None:
if key not in self.__dict__:
self.__dict__[key] = value
t3 = text3("wsm")
t3.age = "123"
print(t3.name)#wsm
print(t3.age)#123
__call__
class text:
def __call__(self, **kwargs) -> None:
print("这是一个__call__", kwargs)
t = text()
t(name="dweiwei")#这是一个__call__ {'name': 'dweiwei'}