python_day7 面向对象 组合交互


组合交互的 self 用法
在一个类 中 调用另外一个类
######################
class Dat:
def __init__(self,year,mon,dat):
self.year=year
self.mon=mon
self.dat=dat
def JS(self):
print('%s-%s-%s' %(self.year,self.mon,self.dat))
class Peo(Dat):
def __init__(self,year,mon,dat,name):
Dat.__init__(self,year,mon,dat)
self.name=name
self.shengri=Dat(self.year,self.mon,self.dat)

B=Peo(1990,9,5,'la')
B.shengri.JS()
############################


继承后,子类的函数会  覆盖 基类的现象
############################
class Foo:
def read(self):
raise TypeError('主动的')
# print('正在打印')

class Foo1(Foo):

def read(self):
print('正在打印')

class Foo2(Foo):
def read(self):
print('正在打印')

class Foo3(Foo):
pass


A=Foo1()
B=Foo2()
C=Foo3()
A.read()
B.read()
C.read()
G=Foo()
G.read()
########################################
虽然上面方法 子类在调用 基类的方法是 会报错
但是 如果 不调用 方法 则就不会报错咯,
下面 展示一种 就算不调用 方法 也会报错的 模块
也就是 抽象类
###################################
import abc

class Foo(metaclass=abc.ABCMeta):
@abc.abstractclassmethod
def read(self):
raise TypeError('主动的')
# print('正在打印')

class Foo1(Foo):
def read(self):
print('正在打印')
class Foo2(Foo):
pass

A=Foo1()
B=Foo2()
以上这种 不执行B=Foo2() 的时候 是正常的,
但是 实例化B 的时候 就报错了,也就是上面说的 现象
#####################
super 函数的用法:
super(). 调用父类的 函数名,
###########################
class Foo:
def read(self):
print('正在打印111111')

class Foo1(Foo):
def read(self):
print('正在打印')
class Foo2(Foo):
def read(self):
super().read()

A=Foo1()
B=Foo2()
B.read()
############









原文地址:https://www.cnblogs.com/onda/p/7001500.html