1.多继承就是一个类继承多个类的属性,调用其中的方法或者属性
class d1:
def __init__(self):
self.money=200e8
self.goal="it is noting"
def str(self):
print("qiongbikuaigun")
class d2:
def __init__(self):
self.bmoney=200
self.bgoal="everyting is wrong"
def str(self):
print("woshiqiongbi")
class d3(d1,d2):
def __init__(self):
#属性与初始化的顺序有关,方法与继承顺序有关
super().__init__()#super是一个对象,不是类所以后面不需要self
d2.__init__(self)#d2是一个类,init后面需要self
h=d3()
print(h.bgoal)
print(h.bmoney)
print(h.goal)
print(h.money)
h.str()
执行结果:
2.私有变量是不能继承的
class 爹:
def __init__(self):
self.__wife="娘"
class 儿:
def __init__(self):
super().__init__()
d=儿()
print(dir(爹))
print(d.__wife)#私有变量不可继承
结果:
儿子没有wife的属性
3.最大的类还得是我“object”:
class my:
pass
class my(object):#所有类都是object 的子孙
pass
m=my()
m1=my()
print(dir(m))
print(dir(m1))
结果:
可见是一模一样的
4.类的属性:
class d1:
"""这里是doc"""
def __init__(self):
self.money=200e8
self.goal="it is noting"
def str(self):
print("qiongbikuaigun")
print(d1.__doc__)#说明
print(d1.__dict__)#所有类的属性放在字典
print(d1.__name__)#类名
print(d1.__bases__)#类的父类
print(d1.__base__)#类的父类
print(d1.__module__)#开始执行的地方
运行结果:
5.super()方法:
# class 爷:
# def __init__(self):
# print("爷构造了一次")
# class 大(爷):
# def __init__(self):
# 爷.__init__(self)
# print("大一次")
# class 中(爷):
# def __init__(self):
# 爷.__init__(self)
# print("中一次")
# class 小(爷):
# def __init__(self):
# 爷.__init__(self)
# print("小一次")
# class 结合(大,中,小):
# def __init__(self):
# 大.__init__(self)
# 中.__init__(self)
# 小.__init__(self)
# 组合=结合()
#此种方法,爷用了三次,浪费内存
class 爷:
def __init__(self):
print("爷构造了一次")
class 大(爷):
def __init__(self):
super().__init__()
print("大一次")
class 中(爷):
def __init__(self):
super().__init__()
print("中一次")
class 小(爷):
def __init__(self):
super().__init__()
print("小一次")
class 结合(大,中,小):
def __init__(self):
super().__init__()
组合=结合()
#此类方法用了解决了爷调用三次问题,实现的是都执行一次。
结果:
可以看出两者的运行结果不同。
6.isinstence
class father:
pass
class son(father):
pass
print(isinstance(father(),father))
print(isinstance(son(),father))#判断子类属于父类,isinstence
print(type(father())==father)
print(type(son())==father)#type进行严格检查
结果:
7.多态:
class serve:
pass
class makeapple(serve):
def make(self):
serve.__init__(self)
print("apple")
class makeorange(serve):
def make(self):
serve.__init__(self)
print("orange")
def makeserve(obj):
obj.make()
#多态用于代码拓展性
m1=makeapple()
makeserve(m1)
m2=makeorange()
makeserve(m2)
结果:
多态的适用于拓展业务的拓展,如果我初始化的工作是输出橘子,但是需求是一直会变的,后面需要草莓等其他的,我使用多态就能一直创造下去,不用重新写代码。
多态是在一个大类的前提下开辟一些小类,执行功能。
一个接口,多个实现。
8.静态方法:
class people:
def __init__(self,tall):
self.tall=198
@staticmethod
def name():
return "joy"
print(people.name())#静态方法不用实例化能调用
p1=people(198)#实例化之后也能用
print(p1.tall)
静态方法不常用,主要特征就是可以不用实例化就能调用类中的东西
9.类方法:
class d1:
def __init__(self):
self.money=200e8
self.goal="it is noting"
@classmethod #类方法,可有可无
def str(self):
print("qiongbikuaigun")
def goal(self):
print("哈哈哈")
def getmoney(wjn):#类方法,把类当作参数
return wjn.money
dawang=d1()
print(getmoney(dawang))
类方法的重点是把类当作一个参数,执行。