首页 > 编程语言 > 详细

python 继承

时间:2021-07-23 11:06:19      阅读:20      评论:0      收藏:0      [点我收藏+]

1. Python继承

继承表示允许我们继承另一个类的所有方法和属性的类。

父类是继承的类,称基类。

子类是从另一个类继承类,称派生类。

 

2. 创建父类

任何类都可以是父类。

实例

创建一个 Person 类,其中包含 firstname lastname 属性以及 printname 方法。

class Person():
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

x = Person(Bill, Gates)
x.printname()

Bill Gates

 

3. 创建子类

创建子类时将父类作为参数发送:

实例

创建一个 Student 类,将从 Person 类继承属性和方法。

class Student(Person):
    pass

现在,Student 类与 Person 类有相同的属性和方法。

注释:不想在类中使用其他属性或方法,使用 pass 关键字。

# 使用 Student 类创建一个对象,执行 printname方法
x = Student(wang, ke)
x.printname()

wang ke

 

4. 添加 __init__() 函数

我们已经创建一个子类,它继承了父类的属性和方法。

下面我们把  __init__() 函数添加到子类。

注释:每次使用类创建新对象,都会调用 __init__() 函数。

实例

Student 类添加 __init__() 函数:

class Student(Person):
    def __init__(self, fname, lname):
        # 添加属性

当添加 __init__() 函数时,子类将不再继承父的 __init__() 函数

注释:子类的 __init__() 函数会覆盖父类的 __init__() 函数。如需保持父类的 __init__() 函数,添加对父类 __init__() 函数的调用。

实例

class Person():
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

class Student(Person):
    def __init__(self, fname, lname):
        Person.__init__(self, fname, lname)

x = Student(wang, ke)
x.printname()
x = Person(Bill, Gates)
x.printname()

wang ke
Bill Gates

 

已经成功添加 __init__() 函数,并保留父类的继承,接下来在 __init__() 函数中添加功能。

 

5. supper() 函数

supper() 函数使子类从父类继承所有方法和属性:

class Person():
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

class Student(Person):
    def __init__(self, fname, lname):
        super().__init__(fname, lname)

x = Student(wang, ke)
x.printname()

wang ke

 

使用 supper() 函数,不必使用父元素的名称,它将自动从父元素继承方法和属性。

 

6. 添加属性

 

python 继承

原文:https://www.cnblogs.com/keye/p/15046883.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!