类的派生,组合

派生:

子类也可以添加自己新的属性或者在自己这里重新定义这些属性(不会影响到父类),需要注意的是,一旦重新定义了自己的属性且与父类重名,那么调用新增的属性时,就以自己为准了。

class Parent():
    def process(self):
        raise TypeError("you should define self")



class Son(Parent):
    pass

s=Son()
s.process()

Traceback (most recent call last):
File "F:/back02/interactiveclass.py", line 83, in <module>
s.process()
File "F:/back02/interactiveclass.py", line 75, in process
raise TypeError("you should define self")
TypeError: you should define self


class Parent():
def process(self):
raise TypeError("you should define self")



class Son(Parent):
def process(self): #自己重新定义父类的process,调用时用自己的
print("my process")

s=Son()
s.process()

my process


class Parent():
    def process(self):
        raise TypeError("you should define self")
    def hello(self):
        return 123


class Son(Parent):

    def process(self):
        print("my process")
        print(Parent.hello(self))      #使用父类定义的

s=Son()
s.process()
class Parent():
    def process(self):
        raise TypeError("you should define self")
    def hello(self):
        return 123


class Son(Parent):
    def hello(self):
        print('myhello')

    def process(self):
        print("my process")
        print(Parent.hello(self))
        self.hello()                 #使用自己的

s=Son()
s.process()

 组合:

组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合

class foo1():
    def __init__(self,name,age):
        self.name=name
        self.age=age

class foo2():
    def __init__(self):
        self.obj=foo1('wes',13)    #self.obj foo1()的一个对象,所以self.obj(s.obj)具有foo1()对象的所有属性,也可以调用foo1类的方法


s=foo2()
print(s.obj.name)

wes


class foo1():
def __init__(self,name,age):
self.name=name
self.age=age
def func(self):
print('foo1.func')

class foo2():
def __init__(self):
self.obj=foo1('wes',13)


s=foo2()
print(s.obj.name)
s.obj.func()

wes
foo1.func



原文地址:https://www.cnblogs.com/wuxi9864/p/9932893.html