gpt4 book ai didi

android - 从现有实例调用方法

转载 作者:太空狗 更新时间:2023-10-29 16:37:52 24 4
gpt4 key购买 nike

我对面向对象编程的理解有点不稳定,所以如果您有任何有助于解释这些概念的链接,我会很高兴看到它们!

我已经稍微缩短了代码。基本原则是我有一个以主 Controller 类的实例开始的游戏。当游戏打开时,Popup 类被打开。事件发生如下:

  1. 单击弹出窗口上的开始按钮
  2. 方法 start_click() 运行
  3. 调用Controller实例中的start_game()方法
  4. 这又将原始 Controller 实例中的游戏状态更改为“True”

我的问题出在第 3 步。我收到的错误消息是:

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

我想 StartPopUp 类中需要引用 Controller 类。但我不太明白如何创建该引用?

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

在 Controller 中

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

关于android - 从现有实例调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23994233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com