python教程 面向对象 继承


类的继承
如果已有一个旧类,我们想创建一个新类,新类所需的功能在旧类中大部分都已经有了,那么我们可以采用继承的方式来创建新类
class Student(Person):
pass

一:子类继承父类属性

子类会继承父类的所有信息—包括属性

class Person: #class定义一个类

age = 23

def __init__(self, name):    #__init__用于初始化,self指向对象,这是python的固定格式。

    self.name = name

Me = Person(“bob”)

print(Me.name)

class Student(Person):

pass

stu1 = Student(“Jack”)

print(stu1.name)

print(stu1.age)

二、子类继承父类方法

子类会继承父类的所有信息—包括方法

扫描二维码关注公众号,回复: 5475271 查看本文章

class Person: #class定义一个类

age = 23

def __init__(self, name):    #__init__用于初始化,self指向对象,这是python的固定格式。

    self.name = name

def myprint():

    print("Hello, I am here.")

class Student(Person):

pass

Student.myprint()

三、子类覆盖父类方法

父亲已有一个方法,子类重写了该方法。

class Person: #class定义一个类

age = 23

def __init__(self, name):    #__init__用于初始化,self指向对象,这是python的固定格式。

    self.name = name

def myprint():

    print("Hello, I am here.")

class Student(Person):

def myprint():

    print("NO NO NO, I am here")

stu1 = Student(“Jack”)

Student.myprint()

猜你喜欢

转载自blog.csdn.net/eisenhowerlong/article/details/88367866