【问题标题】:How do I call a function from one class in another?如何从一个类中调用另一个类的函数?
【发布时间】:2016-01-09 07:47:46
【问题描述】:

我很难理解如何将函数或方法从一个类调用到另一个类。换句话说,如何从Player类中的House类中调用mailbox函数,这样当我输入mailbox时,字符串"There is an old mailbox"就被打印出来了?

class House(object):

    def __init__(self, mailbox, door, vindov):
        self.house = House()
        self.mailbox = mailbox
        self.door = door
        self.vindov = vindov

    def door(self):
        print "There is nothjing special about this door"

    def vindov(self):
        print "The vindov seems to be half open"

    def mailbox(self):
        print "there is an old mailbox"


class Player(House):

    while True:
        action = raw_input("> ")
        if action == "mailbox":

【问题讨论】:

  • 为什么你需要在播放器中存放你的逻辑?你想在这里解决什么问题,如果你想从House调用mailbox方法,你需要做的就是super().mailbox,这将解决Housemailbox方法。
  • 感谢您的帮助,我正在执行播放器中的逻辑,因为我不知道如何为游戏制作引擎,我可以通过函数完美地做到这一点,但我想也可以用类来做
  • 我正在尝试这个:因为这是一个基于文本的游戏,当用户输入邮箱时,我希望程序打印出字符串“有一个旧邮箱”

标签: python class methods


【解决方案1】:

正如 Games Brainiac 所指出的,您可以直接通过名称调用方法,利用 Player 类是 House 类的子类这一事实。为此,首先您必须在 Player 类中初始化超类 House:

class Player(House):
    def __init__(self):
        House.__init__(self)

这样就可以直接用self.mailbox()调用父类Housemailbox()方法。但是,此时这不起作用,因为您在 House 类中存在命名空间冲突。您正在为方法分配与类属性相同的名称,因此如果您尝试在 Player 类中调用 self.mailbox() ,解释器将理解您正在尝试将字符串属性作为方法调用并抛出以下错误:TypeError: 'NoneType' object is not callable。我建议您像这样重命名方法:

def doorMethod(self):
    print("There is nothjing special about this door")

def vindovMethod(self):
    print("The vindov seems to be half open")

def mailboxMethod(self):
    print("there is an old mailbox")

现在您可以在 Player 类中调用mailboxMethod()。为此,我建议您将此调用打包到另一个函数中,而不是使用 while 循环,如下所示:

def mailboxQ(self):
    action = input("> ")
    if action == "mailbox":
        self.mailbox()

现在为了立即向用户提示问题,您应该在父 class House 初始化之后立即调用 Player class__init__() 方法中的方法。

我还应该说,您可能不想尝试在其内部初始化 House class 的实例,因为这会将您引导至 RuntimeError: maximum recursion depth exceeded while calling a Python object。您调用了一个尚未定义的对象;),因此请从您的代码中删除以下行:

self.house = House()

这些更改应该使您的代码现在可以完全正常运行。

【讨论】:

  • 我总是收到错误 self is not defined?我该怎么办
【解决方案2】:

由于Player 继承自House,您可以通过self.mailbox() 简单地从House 内部播放器中调用mailbox 方法。也可以通过super().<method name in super class>调用超类的方法。

>>> class A(object):
...     def __init__(self, t):
...         self.t = t
...
...     def mailbox(self):
...         print("This is an old mailbox")
>>> class B(A):
...     def new_mailbox(self):
...         self.mailbox()
...
...
...
>>> b = B("hello")
>>> b.new_mailbox()
This is an old mailbox

【讨论】:

  • 我必须在播放器类中创建一个函数才能调用 House 类中的邮箱函数吗?我不能只调用没有新函数的函数吗?如果我不使用继承怎么办?
  • 不,你不能有某种方式来引用超类,那就是self。而且,这不是你做游戏引擎的方式,如果你想做一个有功能的引擎,那也没问题。不要在不需要的地方使用类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
相关资源
最近更新 更多