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

标签 python oop

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

相关文章:

python - 如果我在 __init__.py 中有一些函数如何将此函数导入到当前目录代码中

python - Python 中的正则表达式问题

java - 等于 2 个 Java 对象

javascript - OOP Javascript - "get property"方法是否必要?

python - 如何在 matplotlib 中使用 imshow 将 NaN 值绘制为特殊颜色?

python - 无法打开 Flask 应用程序的 url

python - 如何通过python中的属性从对象列表中选择一个对象

PHP:将静态属性范围限制为特定类

python - 如何让 tkinter 显示这些 un​​icode 字符?

PHP OOP 简单计算器制作