1. 程式人生 > >面向物件-繼承、重用性

面向物件-繼承、重用性

class Parentclass1:
    pass


class ParentClass2:
    pass


class SubClass1(Parentclass1):  # 單繼承
    pass


class subClass2(Parentclass1, ParentClass2):  # 多繼承
    pass

繼承:子類繼承父類,可以分為單繼承,與多繼承。子類繼承父類,可以減少重複程式碼。

class Hero:
    def __init__(self,nickname,life_value,aggresivity):
        self.nickname
=nickname self.life_value=life_value self.aggresivity=aggresivity def attack(self,enemy): enemy.life_value -= self.aggresivity class Garen(Hero): pass g1 = Garen('d',29,30) print(g1.__dict__) # print(g1.x) # 先在物件這邊找,再在物件類找,再在父類找 #屬性查詢 先在物件這邊找,再在物件類找,再在父類找! class
Foo: def f1(self): print('from Foo.f1') def f2(self): print('from Foo.f2') self.f1() class Bar(Foo): def f1(self): print('from Bar.f2') b = Bar() b.f2()