gpt4 book ai didi

python - 是否可以从 Python 中的内置函数类进行扩展?

转载 作者:行者123 更新时间:2023-11-28 18:49:32 24 4
gpt4 key购买 nike

既然在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com