Python 如何在类中保存变量,而不使变量因类继承而丢失
我希望它能够在Python 如何在类中保存变量,而不使变量因类继承而丢失,python,class,oop,Python,Class,Oop,我希望它能够在StopSign类中调用active()函数时,调用Car类中的stop()函数。然而,在我实际的代码中(代码有点长,令人分心,所以我使用了这个代码,这样你就可以理解了),当我调用active函数StopSign对象没有属性“movement\u code”。我怎样才能避开这件事 class Car: def __init__(self): self.color = blue more code def go(self):
StopSign
类中调用active()
函数时,调用Car
类中的stop()
函数。然而,在我实际的代码中(代码有点长,令人分心,所以我使用了这个代码,这样你就可以理解了),当我调用active
函数StopSign对象没有属性“movement\u code”
。我怎样才能避开这件事
class Car:
def __init__(self):
self.color = blue
more code
def go(self):
self.movement_code = movement_function
def stop:
self.movement_code.kill()
class StopSign(car):
def __init__(self):
some code
def active(self):
self.stop()
您遇到的问题是
StopSign
没有初始化其父类,因此没有继承stop
方法。除此之外,尽管我同意雅利娅的观点。让StopSign
类继承自Car
类是没有意义的
class Car:
def __init__(self):
self.color = 'blue'
# more code
def go(self):
pass
# self.movement_code = movement_function
def stop(self):
pass
# self.movement_code.kill()
class StopSign(Car):
def __init__(self):
super().__init__()
pass
# some code
def active(self):
self.stop()
sign = StopSign()
sign.active()
下面是一个简单的示例,说明如何避免使用StopSign
子类Car
:
class Car:
def __init__(self):
self.color = 'blue'
def go(self):
pass
def stop(self):
pass
class StopSign:
def __init__(self):
self.cars_in_vicinity = []
def active(self):
for car in self.cars_in_vicinity:
car.stop()
car = Car()
sign = StopSign()
sign.cars_in_vicinity.append(car)
sign.active()
不过,还有很多其他方法可以解决这个问题。这里有一些语法问题,但也有一个类设计问题。停车标志不是汽车,所以它不应该继承自汽车。@aryamcarthy那么我如何访问
stop
函数而不必再次初始化汽车类呢?