入门python如何成为重写大神

ε祈祈猫儿з 提交于 2020-03-09 03:15:41

类方法重写对于学好python非常重要,除了python基础,python的精髓在于继承,多态,封装和装饰器;下面是对于继承重写的一个简单示例:

# 父类
class Student():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print('我的名字叫{},我今年{}岁了'.format(self.name, self.age))

# 子类
class NewStudent(Student):
    def __init__(self, name, age, sex):
        Student.__init__(self, name, age)
        self.sex = sex
	
	# 重写父类introduce方法,是父类中的introduce失效
    def introduce(self):
        print('我的名字叫{},我今年{}岁了, 我是{}孩。'.format(self.name, self.age,self.sex))


s = NewStudent('小明', 18, '男')
s.introduce()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!