Python中不常见OOP的原因是什么?

2024-06-08 02:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

Python没有像Java和C那样对基类Object或{}使用通用的OOP,而是使用特殊的方法来处理对象的基本行为。Python使用__str__,当对象被传递到print时使用:

>>> class Demo:
>>>   def __str__(self):
>>>     return "representation"

>>> d = Demo()
>>> print(d)
representation

len相同:

^{pr2}$

我所期望的是:

>>> class Ruler:
>>>   def len(self):
>>>     return 42

>>> r = Ruler()
>>> r.len()
42

为什么要间接使用特殊方法而不是直接调用普通方法?在


Tags: 对象方法selflenreturnobjectdemodef
3条回答

这些不是钩子。在

它们只是具有特殊名称的方法。在

Python中特殊方法名的约定是__name__。在

内置的len、iter、str、repr(和其他)函数使用普通方法,这些方法的名称遵循一个特殊的约定,这样我们就可以确保我们已经正确地实现了这些特殊方法。在

特殊的方法有奇怪的名字,所以我们可以自由使用任何我们想要的名字,而不必担心冲突。在


obj.len() would be much more intuitive to implement and use.

也许是为了你。对其他人来说,这可能完全令人困惑。在

Python对许多常见函数都有方法表示法和函数表示法。在

最好使用函数表示法。在

它仍然是面向对象编程。只改变了符号。在

这里的Python文档对其原因进行了很好的解释:

http://docs.python.org/faq/design.html#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list

The major reason is history. Functions were used for those operations that were generic for a group of types and which were intended to work even for objects that didn’t have methods at all (e.g. tuples). It is also convenient to have a function that can readily be applied to an amorphous collection of objects when you use the functional features of Python (map(), apply() et al).

In fact, implementing len(), max(), min() as a built-in function is actually less code than implementing them as methods for each type. One can quibble about individual cases but it’s a part of Python, and it’s too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.

(这在评论中得到了回答,但为了将来的读者,需要将其作为真实答案显示出来。)

钩子允许重新定义标准函数的行为。考虑重写__add__()并使用标准中缀+运算符,而不是添加自定义add()并使用嵌套调用。在

此外,如果定义__iter__(),则可以在for ... in循环中使用对象。将其与控制循环和手动推进迭代相比较。考虑重写__call__()并将实例转换为函数,与其他函数一样好。这给了我们极大的灵活性。在

如果您愿意,Java对.toString()也做了同样的处理,当您打印对象或将其连接到一个字符串时,它隐式地工作。在

相关问题 更多 >

    热门问题