4

由于一切都是 Python 中的对象(甚至是函数),是否可以从函数类实际扩展?例如,我可以使用字符串类型执行以下操作。有没有办法在函数类型上做类似的事情?

class Foo(str):
    def appendFoo(self):
        return self+'foo'

foo = Foo('test')
print foo
>>> test
print foo.upper()
>>> TEST
print foo.appendFoo()
>>> testfoo
4

1 回答 1

2

不,我希望。你被函子困住了。

>>> 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
于 2013-02-26T05:58:06.603 回答