既然在 Python 中一切都是对象(甚至是函数),是否可以从函数类实际扩展?例如,我可以使用字符串类型执行以下操作。有什么方法可以在函数类型上做类似的事情吗?
class Foo(str):
def appendFoo(self):
return self+'foo'
foo = Foo('test')
print foo
>>> test
print foo.upper()
>>> TEST
print foo.appendFoo()
>>> testfoo
最佳答案
不,我希望。你被仿函数困住了。
>>> 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
关于python - 是否可以从 Python 中的内置函数类进行扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15082320/