【发布时间】:2015-09-18 16:18:29
【问题描述】:
作为我自己的练习,我正在尝试用 Python 编写一个与 C# 中的事件类似的类。
下面是类中的两个主要函数(__subs 是一个列表):
class Event (object):
def __iadd__ (self, other):
if not callable(other):
raise ValueError("%s must be callable" % other)
self.__subs.append(other)
return self
def __add__ (self, other):
if not callable(other):
raise ValueError("%s must be callable" % other)
new = Event()
new.__subs = [f for f in self.__subs]
new.__subs.append(other)
return new
def __call__ (self, *args, **kwargs):
for func in self.__subs:
func(*args, **kwargs)
这允许以下语法:
e1 = Event()
e1 += afunction
e2 += another
e1 (arg1, arg = val) # afunction and another will be called with arg1 and val
e2 = Event() + afunction + another
e2 (arg1, arg = val)
(Event() + afunction + another) (arg1, arg = val)
但是,我想将最后两个简化成这样
e = afunction + another
e (arg1, arg = val)
(afunction + another) (arg1, arg = val)
我尝试这样做,但我收到错误“TypeError: 'function' is not an accepted base type”
class function (FunctionType):
def __add__ (self, other):
return Event() + self + other
我正在尝试做的事情可能吗?
【问题讨论】:
标签: python function python-2.7 operator-overloading