1. 程式人生 > >python-15 繼承 多型

python-15 繼承 多型

所有類的父類是object

繼承的寫法

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def say_hi(self):
        print("hello I am{0} age{1}".format(self.name,self.age))

class Student(Person):
    def __init__(self,name,age,stu_id):
        Person.__init__(self,name,age)
        self.stu_id = stu_id
        
    def say_hello(self):
        Person.say_hi(self)
        print("stu_id{0}".format(self.stu_id))

s = Student("tom",12,121212121)
s.say_hello()

利用super函式進行父類屬性的初始化 程式碼有問題

class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def say_hi(self):
        print("hello I am{0} age{1}".format(self.name,self.age))

class Student(Person):
    def __init__(self,name,age,stu_id):
        super(Student.self).__init__(self,name,age)
        self.stu_id = stu_id
        
    def say_hello(self):
        super(Student.self).say_hi(self)
        print("stu_id{0}".format(self.stu_id))

s = Student("tom",12,121212121)
s.say_hello()

類的繼承關係

class A:
    pass
class B(A):
    pass

class C(B):
    pass

class D(A):
    pass
class E(B,D):
    pass

print(B.mro())
print(E.__mro__)

[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

(<class '__main__.E'>, <class '__main__.B'>, <class '__main__.D'>, <class '__main__.A'>, <class 'object'>)

方法的重寫

java裡面的定義:名字相同,引數列表相同,返回值相同
子類的方法不能比父類更嚴格的許可權

class D:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def area(self):
        pass

class C(D):
    def __init__(self,r):
        D.__init__(self,r,0)
    def area(self):
        return 3.14*self.x*self.x

class R(D):
    def __init__(self,w,h):
        D.__init__(self,w,h)
    def area(self):
        return self.x*self.y

c = C(3)
print(c.area())
r = R(3,4)
print(r.area())

28.259999999999998
12

一種錯誤的示範

class D:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def area(self):
        pass


class R(D):
    def __init__(self,w,h):
        D.__init__(self,w,h)
    def __area(self):
        return self.x*self.y


r = R(3,4)
print(r.area())

None

呼叫的是父類裡面的area方法

多型

1.方法的過載與重寫
2.運算子的過載