如何在继承另一个类python的另一个类的类中使用一个方法 [英] How to use a method in a class from another class that inherits from yet another class python

查看:747
本文介绍了如何在继承另一个类python的另一个类的类中使用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个类:

  class Scene(object):
def enter $ b pass

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

class Map(object):
def __init __(self,start_game):
pass

类映射:

  a_map = map('central_corridor')

这意味着有一个地图(显然不像一个迷宫让我们假设的图形),其中游戏的第一个场景(游戏像zork)是中央走廊。 p>

所以我想在地图类中使用类CentralCorridor的enter方法,但我很困惑的事实,CnetralCorridor类本身继承自类Scene。我不知道如何使用如下所述的委派方法: http://stackoverflow.com/a/2797332/2572773

解决方案

1)Python类以一个大写字母开头是一个好习惯。
此外,名称 map 是一个内置的python函数。



2)映射类?

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

a_map = Map(CentralCorridor())


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 : http://stackoverflow.com/a/2797332/2572773

解决方案

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())

这篇关于如何在继承另一个类python的另一个类的类中使用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆