dze*_*siz 3 python inheritance overriding
我在Python中遇到了难以继承的问题,但我知道它是如何工作的,因为我在Java方面有了较大的经验......为了清楚起见,我在这里搜索了问题以及在线文档,所以我知道这将是在瞬间被称为重复的问题:P
我在Codecademy上的代码传递方式如下:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
def display_car(self):
return "This is a %s %s with %s MPG." % (self.color, self.model, self.mpg)
def drive_car(self):
self.condition = "used"
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
Run Code Online (Sandbox Code Playgroud)
但据我所知,我几乎要定义一个新类......那里的继承是什么?我可以这样做:
class ElectricCar(Car):
def __init__(self, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
Run Code Online (Sandbox Code Playgroud)
也许带有关键字的东西
super
Run Code Online (Sandbox Code Playgroud)
?
您可以调用Car init方法并传递其参数
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
Car.__init__(self,model,color,mpg)
self.battery_type = battery_type
Run Code Online (Sandbox Code Playgroud)
或者您也可以使用super评论中提到的首选方法.
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
super(ElectricCar,self).__init__(model, color, mpg)
self.battery_type = battery_type
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1167 次 |
| 最近记录: |