I want a class to call my function on a certain event. My question is, is it good practice to check for "None" to check if the Function "Pointer" has been initialized? Are there any other gotchas using this pattern?
In class:
class Consumer(object):
_functionCallBack = None
def __init__(self, hostName):
self._hostName = hostName
def SetCallBack(self, funcCallback):
self._functionCallBack = funcCallback
def HandleMessage(self, body):
print(" [x] Received %r" % body)
if self._functionCallBack is not None:
self._functionCallBack(body)
In calling code:
def handleMessageReceived(message):
print("In call back", message);
def main():
Consumer = Consumer("hostname")
consumer.SetCallBack(handleMessageReceived)
consumer.Start()
if __name__ == "__main__" : main()
I was unable to find any best practices for this - if there are some in the Python docs can you let me know.
_functionCallBack = Nonebe part of the__init__method?global _functionCallBackinside every function that changes its value.self, and not inside a class. AFAIK, if you want to change it inside a function, then you need to declare itglobalin that function.