I'm new in Python with a strong background in Objective-C and Swift.
In swift you can create optional closures that could be use as callback. Here is a example:
class Process {
// The closure that will be assigned by the caller of Process.
var didSuccess: ((Bool)->())?
func run() {
let isSuccess = true
didSuccess?(isSuccess) // If closure is assigned we call it.
}
}
class Robot {
private var process = Process()
init() {
process.didSuccess = examineProcess // We assign the closure
}
func examineProcess(result: Bool) {
print("The result is: \(result)")
}
func run() {
process.run()
}
}
let superPower = SuperPower()
superPower.run()
As we can see when we will call 'superPower.run()' the output will be The result is: true
Is there an equivalent pattern in Python?
Michael Butscher posted an answer but I improved it because it could lead to some bugs.
This is the solution I use:
class Process:
def __init__(self):
self.didSuccess: Callable[[bool], None] = None
def run(self):
if self.didSuccess is not None and callable(self.didSuccess):
# we are sure that we will be able to call didSuccess and avoid bugs
# caused by `myInstance.didSuccess = 3` for example
self.didSuccess(True)
class Robot:
def __init__(self):
self.__process = Process()
self.__process.didSuccess = examineProcess
# or lambda
self.__process.didSuccess = lambda x: print("The result is: ", x)
func examineProcess(bool, result: bool):
print("The result is: ", result)
def run(self):
self.__process.run()
I do double check on the attribute with if self.didSuccess is not None and callable(self.didSuccess)
to be sure that the attribute is callable.
There is no real support for this. You can write something like
didSuccess(True) if didSuccess else None
In the shell this looks like:
>>> didSuccess = None
>>> didSuccess(True) if didSuccess else None
>>> didSuccess = lambda b: print("The result is: {}".format(b))
>>> didSuccess(True) if didSuccess else None
The result is: True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.