从现有实例中调用方法

编程入门 行业动态 更新时间:2024-10-28 09:22:19
本文介绍了从现有实例中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对面向对象编程的理解有些不稳定,因此,如果您有任何链接可以帮助解释这些概念,那么很高兴看到它们!

My understanding of Object Orientated Programming is a little shaky so if you have any links that would help explain the concepts it would be great to see them!

我已经将代码缩短了一些.基本原则是,我有一个游戏开始于主Controller类的实例.打开游戏后,将打开Popup类.这些事件发生如下:

I've shortened the code somewhat. The basic principle is that I have a game that starts with an instance of the main Controller class. When the game is opened the Popup class is opened. The events happens as follows:

  • 单击弹出窗口上的开始按钮
  • start_click()方法运行
  • 在Controller实例中调用方法start_game()
  • 依次将原始Controller实例中的游戏状态更改为"True"
  • 我的问题出在步骤3.我收到的错误消息是:

    My problem is with step 3. The error message I get is:

    TypeError: unbound method start_game() must be called with Controller instance as first argument (got nothing instead)

    我猜想在StartPopUp类中需要对Controller类有一些引用.但是我不太了解如何创建该引用?

    I guess there needs to be some reference to the Controller class in the StartPopUp class. But I don't quite understand how to create that reference?

    import kivy kivy.require('1.8.0') from kivy.app import App from kivy.uix.widget import Widget from kivy.clock import Clock from kivy.properties import BooleanProperty, NumericProperty, ObjectProperty from kivy.uix.popup import Popup from kivy.lang import Builder Builder.load_string(''' <StartPopUp> size_hint: .2, .2 auto_dismiss: False title: 'Welcome' Button: text: 'Play' on_press: root.start_click() on_press: root.dismiss() ''') class StartPopUp(Popup): def __init__(self, **kw): super(StartPopUp, self).__init__(**kw) def start_click(self): Controller.start_game() class Controller(Widget): playing_label = BooleanProperty(False) #Intitial phase of game is off def __init__(self, **kw): super(Controller, self).__init__(**kw) def start_popup(self, dt): sp = StartPopUp() sp.open() def start_game(self): self.playing_label = True print self.playing_label class MoleHuntApp(App): def build(self): game = Controller() Clock.schedule_once(game.start_popup, 1) return game if __name__ == '__main__': MoleHuntApp().run()

    提前谢谢!

    推荐答案

    您可以像这样传递实例

    class StartPopUp(Popup): def __init__(self, controller, **kw): super(StartPopUp, self).__init__(**kw) self.controller = controller def start_click(self): self.controller.start_game()

    并在控制器中

    def start_popup(self, dt): sp = StartPopUp(self) sp.open()

    更多推荐

    从现有实例中调用方法

    本文发布于:2023-11-17 03:43:21,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1608696.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:实例   方法

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!