公司集团网站开发,网站后台更新后前台没有同步更新,泉州网站建设策划,wordpress如何添加友情链接版权所有#xff0c;未经许可#xff0c;禁止转载Python 继承继承允许我们在定义一个类时#xff0c;让该类继承另一个类的所有方法和属性。父类是被继承的类#xff0c;也称为基类。子类是继承父类的类#xff0c;也称为派生类。创建父类任何类都可以是父类#xff0c;创…版权所有未经许可禁止转载Python 继承继承允许我们在定义一个类时让该类继承另一个类的所有方法和属性。父类是被继承的类也称为基类。子类是继承父类的类也称为派生类。创建父类任何类都可以是父类创建父类的语法和创建普通类是一样的:示例创建一个名为Person的类包含属性firstnamelastname, 方法printname:class Person:def __init__(self, fname, lname):self.firstname fnameself.lastname lnamedef printname(self):print(self.firstname, self.lastname)# 使用Person类创建对象然后执行printname方法:x Person(Kevin, Wu)x.printname()创建子类要创建子类需将父类作为参数传入:示例创建一个名为Student的类它将继承Person类的属性和方法:class Student(Person):pass注意: 当您不想给类添加任何属性或方法时使用pass关键字。现在Student类具有与Person类相同的属性和方法。示例使用Student类创建对象然后执行printname方法:x Student(Kevin, Tony)x.printname()添加__init__()函数到目前为止我们已经创建了一个子类它继承了父类的属性和方法。现在将__init__()函数添加到子类(不再使用pass关键字)。注意: 每当创建新对象时都会自动调用类的__init__()函数。示例将__init__()函数添加到Student类:class Student(Person):def __init__(self, fname, lname):# 添加属性当您添加了__init__()函数后子类将不再继承父类的__init__()函数。注意: 子函数的__init__()重写父函数的__init__()。要保留父类的__init__()函数的功能可在子类的__init__()函数中调用父类的__init__()函数:示例class Student(Person):def __init__(self, fname, lname):Person.__init__(self, fname, lname)现在我们已经给子类添加了__init__()函数并调用了父类的__init__()函数下面我们将在__init__()函数中添加其他功能。添加属性示例在Student类中添加一个关于毕业年份的属性:class Student(Person):def __init__(self, fname, lname):Person.__init__(self, fname, lname)self.graduationyear 20192019年应该是一个变量并在创建学生对象时传递给Student类。为此在__init__()函数中添加另一个year参数:示例添加一个year参数创建对象时传入毕业年份:class Student(Person):def __init__(self, fname, lname, year):Person.__init__(self, fname, lname)self.graduationyear yearx Student(Kevin, Tony, 2019)加入方法示例在Student类中添加一个名为welcome的方法:class Student(Person):def __init__(self, fname, lname, year):Person.__init__(self, fname, lname)self.graduationyear yeardef welcome(self):print(Welcome, self.firstname, self.lastname, to the class of, self.graduationyear)如果在子类中添加父类中的同名方法则父类的方法将被重写。