为什么我不能在我的方法中只运行一行一次?



因此,作为游戏的一部分,我有一个动画文本窗口,每秒都会弹出并打印每个单词。

这里的问题是方法"eachwordprint",在游戏中被反复调用,但我只想运行newmessage.text.split一次。 我只是把它放在 init 中,但在游戏中,我在不同的时间更改字符串,所以我每次更改字符串时都需要拆分字符串。

我试过做

if self.counter <=1:
    words = newmessage.text.split(' ')

但这不起作用(我不知道为什么)。 关于如何更好地实现我想要做的事情的任何建议?

class NewLabel(ButtonBehavior, Label):
    def __init__(self, **kwargs):
        super(NewLabel, self).__init__(**kwargs)
        self.font_name='PressStart2P.ttf'
        self.font_size=16
        self.text=kwargs['text']
        self.text_size=(Window.width*.70, Window.height*.23)
        self.mipmp = True
        self.line_height=1.5
        self.markup = True
        self.counter=0
        #self.words = self.text.split(' ')

    def eachwordprint(self, *args):
        self.counter += 1
        if self.counter <=1:
            words = newmessage.text.split(' ')
        print "counter: ", self.counter
        print "word length", len(words)
        if self.counter <= 1:
            anim = Animation(size_hint=(1, .25), duration=1.8)
            anim.start(messagebox)
            self.text=''
        if len(words) > self.counter:
            self.text += words[self.counter]
            self.text += " "
        else:
            anim2 = Animation(size_hint=(1, 0), duration=1.8)
            anim2.start(messagebox)
            #messagebox.remove_widget(self)
            return False
newmessage = "this is a test hello. this is a test."

你可以记住拆分的输出

MC = {}

def wrapper(fn):
    def inner(arg):
        if not MC.has_key(arg):
            MC[arg] = fn(arg)
        return MC[arg]
    return inner
@wrapper
def myfn(x):
    print x
myfn(1)
myfn(1)
myfn(2)

所以基本上发生的事情是你像这样编写文本拆分函数

@wrapper
def split(text):
    return text.split(' ')
每次你想要拆分newmessage.text

时,你称之为split(newmessage.text)。包装器将首先检查文本是否已经遇到,如果是,则返回值,或者调用函数并将其拆分并存储以供以后使用。

您可以在此处运行上述代码 http://codebunk.com/b/-JJzVKR8KgtdaIIsmODh

如果你的newmessage被不需要知道NewLabel实例的其他代码部分修改,我可能会创建一个类来封装newmessage行为:

class Message(object):
    def __init__(self, message):
        self.set_text(message)
    def set_text(self, message):
        self.text = message.split(' ')
newmessage = Message("this is a test hello. this is a test.")

然后将其作为传递给NewLabel的参数之一:

class NewLabel(ButtonBehavior, Label):
    def __init__(self, **kwargs):
        ...
        self.message = kwargs['message']
    def eachwordprint(self, *args):
        words = self.message.text
        print "counter: ", self.counter
        print "word length", len(words)
        ...

每当您需要更改消息时,您都可以执行以下操作:

newmessage.set_text('this is the new test')

但是,如果您总是在知道您的NewLabel的代码部分中设置消息文本,则只需将它们直接添加到NewLabel类中:

class NewLabel(ButtonBehavior, Label):
    def __init__(self, **kwargs):
        ...
        self.set_text(kwargs['message'])
    def set_text(self, text):
        self.words = text.split(' ')
    def eachwordprint(self, *args):
        words = self.words
        print "counter: ", self.counter
        print "word length", len(words)
        ...

最新更新