我正在尝试访问Child类的“Table_Name变量”,以使“Load_Data”方法执行不同的操作,具体取决于投射父类的子项。
还有,有方法知道召唤父类的孩子吗?
public game(){
setFocusable(true);
initGame();
}
public void resetGame() {
initGame();
}
private void initGame() {
gamelooptimer = new Timer(10, this);
gamelooptimer.start();
p = new Player(MainClass.width / 2 - 60, 400);
c = new ControllerEnemy();
r = new ControllerRocket();
e = new ControllerExplosion();
menu = new Menu();
gameover = new GameOver();
addKeyListener(new KeyInput(p));
addMouseListener(new MouseInput());
}
答案 0 :(得分:1)
答案 1 :(得分:1)
我认为你要做的是这样的事情:
{{1}}
在某些情况下,这种模式是完全可以接受的,但很难从你的伪代码示例来判断你正在尝试做的是其中一种情况。
答案 2 :(得分:0)
在子类上实现load_data
。像这样:
class Child1(Base):
...
def load_data():
# CHILD1's OWN LOGIC
class Child2(Base):
...
def load_data():
# CHILD2's OWN LOGIC
(根据您的评论更新。)
如果所有子类都需要不同的逻辑,则必须为每个子项编写该逻辑。但是,如果您只有一些例外,那么您只能为那些方法覆盖该方法。
但是如果只有几种已知的可能性,那么你可以定义一个类属性,只改变子对象上的那个属性,如下所示:
class Base(obj):
custom_attribute = 'default_value'
def load_data(self):
if self.custom_attribute == SOMETHING:
pass
else:
pass
class Child1(Base):
custom_attribute = 'child1_value'
...
class Child2(Base):
custom_attribute = 'child2_value'
...