因为一切都是Python中的对象(甚至是函数),是否可以从函数类实际扩展?例如,我可以使用字符串类型执行以下操作。有没有办法在函数类型上做类似的事情?
class Foo(str):
def appendFoo(self):
return self+'foo'
foo = Foo('test')
print foo
>>> test
print foo.upper()
>>> TEST
print foo.appendFoo()
>>> testfoo
答案 0 :(得分:1)
>>> def f(): pass
...
>>> type(f)
<type 'function'>
>>> function
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'function' is not defined
>>> function = type(f)
>>> class MyFunc(function):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'function' is not an acceptable base type
>>> type('MyFunc', (function,), {})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type 'function' is not an acceptable base type