python重写_python的继承和重写

"""

class ClassName(baseclasslist):

'''类的帮助信息'''

staement # 类体

ClassName:用于指定类名

baseclasslist:用于指定要继承的基类(也就是父类),可以有多个,类名之间用逗号分隔

"类的帮助信息":用于指定类的文档字符串,定义该字符串后,在创建类的对象时,输入类名和

类的左侧的括号"("后,将显示该信息

statement:类体,主要有类变量,方法和属性等定义语句组成

"""

class Fruit:

color="绿色"

def harvest(self,color):

print("水果是:"+color+"的")

print("水果已经收获!")

print("水果原来是:"+Fruit.color+"的")

class Apple(Fruit):

color = "红色"

def __init__(self):

print("我是苹果")

class Orange(Fruit):

color = "橙色"

def __init__(self):

print("\n我是橘子")

apple=Apple()

apple.harvest(apple.color)

orange=Orange()

orange.harvest(orange.color)

"""

在派生类中定义__init__()方法时,不会自动调用基类的__init__()方法。

例如,定义一个Fruit类,在__init__()方法中创建类属性color,然后在Fruit类中定义一个harvest()方法,在该方法中输出类属性color的值,再创建继承自Fruit类的Apple类,

最后创建Apple类的实例,并调用harvest()方法

"""

class Fruit:

def __init__(self,color="绿色"):

self.color=color

def harvest(self):

print("水果原来是:"+self.color+"的")

class Apple(Fruit):

def __init__(self):

print("我是苹果")

super().__init__() # 在派生类中定义__init__()方法时,不会自动调用基类的__init__()方法。 需要super一下

apple=Apple()

apple.harvest()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值