How to use a method in a class from another class that inherits from yet another class python

和自甴很熟 提交于 2019-12-25 03:00:49

问题


I have 3 classes :

class Scene(object):
    def enter(self):
        pass

class CentralCorridor(Scene):
    def enter(self):
        pass

class Map(object):
    def __init__(self, start_game): 
        pass

And the class map is initiated like this :

a_map = map('central_corridor')

It means that there is a map(obviously not graphical like a maze let's suppose) in which the first scene of the game(the game is like zork) is central corridor.

So I want to use the enter method of the class CentralCorridor in the map class but I am confused by the fact that the class CnetralCorridor itself inherits from the class Scene. I don't know how can I use the delegation method as explained here : https://stackoverflow.com/a/2797332/2572773


回答1:


1) It's a good practice for Python classes to start with an uppercase letter. Furthermore, the name map is a built-in python function.

2) what's wrong with passing a Scene instance on your map class?

class Map(object):
    def __init__(self, scene):
        self.scene = scene
    def enter(self):
        self.scene.enter()

a_map = Map(CentralCorridor())



回答2:


Would this code help:

class Scene(object):
    def enter(self):
        print 'Scene Object'

class CentralCorridor(Scene):
    def enter(self):
        print 'CentralCorridor object'

class Map(object):
    def __init__(self, start_game):
        self.start_game = start_game
        if self.start_game == 'central_corridor':
            whatever = CentralCorridor().enter()

a_map = Map('central_corridor')

You should not use map, but Map instead, because map() is a build-in function




回答3:


First, you should rename your map class, since map is a builtin function you'll shadow here.

To answer your question: you can call CentralCorridor.enter(self) to explicitly call CentralCorridor's enter method on the current instance (which does not have to be a CentralCorridor instance).



来源:https://stackoverflow.com/questions/23245149/how-to-use-a-method-in-a-class-from-another-class-that-inherits-from-yet-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!