class Person(object):
#重写发生在继承之间
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return ("name:%s,age:%d"%(self.name,self.age))
def show(self):
print("我是Person的方法")
xiaoHong = Person("小洪",18)
xiaoHong.show()
print(xiaoHong)
print("----------------")
class Student(Person):
# 重写发生在继承之间
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return ("name:%s,age:%d" % (self.name, self.age))
#当Student类中没有show方法时,就会调用Person父类中的show方法
# def show(self):
# print("我是Student的方法")
xiaoMing = Person("小明", 20)
xiaoMing.show()
print(xiaoMing)
python面向对象中的重写
最新推荐文章于 2024-12-22 18:45:38 发布
本文通过Python代码展示了类的基本定义、初始化方法、字符串表示方法及继承的概念。具体包括Person类与Student子类的创建过程,同时演示了如何在子类中重写父类的方法。
2449

被折叠的 条评论
为什么被折叠?



