【发布时间】:2015-12-11 12:19:06
【问题描述】:
是否存在对应于不带参数、什么都不做、什么也不返回的函数的 python 构造?类似于对象None 但那将是一个函数而不是一个对象?
上下文
我想定义一个类,其中构造函数将函数作为参数并将其引用到类属性。在实例化时,用户决定他/她是否希望该函数成为他/她自己定义的实际函数,或者保留默认值,即调用一个什么都不做的虚拟函数。
这是我现在拥有的:
def sayHello():
print("hello world !")
def doNothing():
pass
class myClass:
def __init__(self, myFunc):
self.doIt = myFunc
myInstance = myClass(sayHello)
myInstance.doIt()
myInstance = myClass(doNothing) # Works but requires defining function doNothing()
myInstance.doIt()
#myInstance = myClass(None) # Returns error "'NoneType' object is not callable"
myInstance.doIt()
【问题讨论】: