2015-03-03 62 views
2

我有一个听起来像委托问题的问题。我有类似下面的代码:我需要一个委托类?

class foo(object): 
    def __init__(self,onEvent1="", onEvent2=""): 
     self.OnEvent1=onEvent1 
     self.OnEvent1=onEvent2 

    def aLoop(self): 
     ... 
     #in case of event1 
     self.OnEvent1() 
     ... 
     #in case of event2 
     self.OnEvent2() 


EventType=0 

def MyBar1(): 
    print("Event Type1") 
    EventType=1 

def MyBar2(): 
    print("Event Type2") 
    EventType=2 

myFoo=foo(MyBar1,MyBar2) 

while True: 
    myFoo.aLoop() 
    if (EventType==1): 
     print ("EventType is 1") 
     EventType=0 
    elif (EventType==2): 
     print ("EventType is 2") 
     EventType=0 

我可以看到print()回调函数中而不是在while循环的消息的print()的消息。 变量EventType不会更改其值。

我能做什么?

回答

1

EventType变量MyBar1MyBar2局部变量。你绑定的任何变量都是本地的,除非另有明确的配置;分配,函数参数,函数或类定义以及名称import都是绑定名称的所有方法。

您需要使用global语句来改变这种:

def MyBar1(): 
    global EventType 
    print("Event Type1") 
    EventType=1 

def MyBar2(): 
    global EventType 
    print("Event Type2") 
    EventType=2 

注意,几乎没有点给你的事件参数为空字符串,默认参数:

def __init__(self,onEvent1="", onEvent2=""): 

如果他们可选,将它们设置为None并测试:

def __init__(self, onEvent1=None, onEvent2=None): 
    self.OnEvent1 = onEvent1 
    self.OnEvent2 = onEvent2 

def aLoop(self): 
    ... 
    #in case of event1 
    if self.OnEvent1 is not None: 
     self.OnEvent1() 
    ... 
    #in case of event2 
    if self.OnEvent2 is not None: 
     self.OnEvent2() 
+0

好,好!我是个傻瓜... – EffegiWeb 2015-03-03 11:34:51

+0

坦克的帮助,即使在传递参数。 我是新的python编程,我通常在c和Vb.net编写程序。 – EffegiWeb 2015-03-04 17:12:02

1
EventType=0 

def MyBar1(): 
    global EventType 
    print("Event Type1") 
    EventType=1 

def MyBar2(): 
    global EventType 
    print("Event Type2") 
    EventType=2 

的问题是,你需要修改全球变量,但你要创建一个本地一个来代替。您仍然可以使用访问全局变量,而不使用global variable。你需要这个到修改吧。

相关问题