入门python如何成为重写大神

类方法重写对于学好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()
发布了47 篇原创文章 · 获赞 18 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/human_soul/article/details/104733648