1. 程式人生 > >Python 呼叫父類方法

Python 呼叫父類方法

____tz_zs未完

python 2.x

老式類的方法

  • 優點:簡潔。
  • 缺點:不能很好的處理菱形繼承。因為你可能會呼叫兩次共享基類的建構函式。
class Human(object):
    def __init__(self, age):
        self.age = age
        print "Human age:%s:" % age


class Student(Human):
    def __init__(self, name, age):
        print "student"
        Human.__init__(self, age)

新式類方法

class Human(object):
    def __init__(self, age):
        self.age = age
        print "Human age:%s:" % age


class Student(Human):
    def __init__(self, name, age):
        print "student"
        super(Student, self).__init__(age)

python 3.x

python 3.5之後,super() 等同於 super(, self),不再需要傳入這兩個引數

class Human(object):
    def __init__(self, age):
        self.age = age
        print("Human age:%s:" % age)


class Student(Human):
    def __init__(self, name, age):
        print("student")
        super().__init__(age)

參考