EffegiWeb
EffegiWeb

Reputation: 184

I need a delegate class?

I have a problem that sounds like a delegation problem. I have a code like the following:

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

I can see the message of the print() inside the callback functions but not the print() of the messages in the while loop. The variable EventType doesn't change its value.

What I can do?

Upvotes: 2

Views: 79

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124258

The EventType variables in MyBar1 and MyBar2 are local variables. Any variable you bind to is a local, unless explicitly configured otherwise; assignments, function parameters, a function or class definition and names you import are all ways to bind a name.

You need to use a global statement to change this:

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

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

Note that there is little point in giving your event arguments an empty string as default argument:

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

If they are optional, set them to None and test for that:

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

Upvotes: 1

ForceBru
ForceBru

Reputation: 44888

EventType=0

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

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

The problem is, you need to modify a global variable, but you're creating a local one instead. You can still access the global variable without using global variable. You need this to modify it.

Upvotes: 1

Related Questions