1 继承
2 创建父类
class Person:def __init__(self, fname, lname):self.firstname = fnameself.lastname = lnamedef printname(self):print(self.firstname, self.lastname)# 使用 Person 来创建对象,然后执行 printname 方法:x = Person("Bill", "Gates")x.printname()
3 创建子类
class Student(Person):pass
x = Student("Elon", "Musk")x.printname()
4 添加 __init__()
函数
class Student(Person):def __init__(self, fname, lname):# 添加属性等pass
class Student(Person):def __init__(self, fname, lname):Person.__init__(self, fname, lname)
5 使用 super()
函数
class Student(Person):def __init__(self, fname, lname):super().__init__(fname, lname)
6 添加属性
class Student(Person):def __init__(self, fname, lname):super().__init__(fname, lname)self.graduationyear = 2019
class Student(Person):def __init__(self, fname, lname, year):super().__init__(fname, lname)self.graduationyear = yearx = Student("Elon", "Musk", 2019)
7 添加方法
class Student(Person):def __init__(self, fname, lname, year):super().__init__(fname, lname)self.graduationyear = yeardef welcome(self):print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
https://blog.csdn.net/weixin_44237659?spm=1011.2124.3001.5343
文章转载自微思研,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




