gpt4 book ai didi

python - 在python中返回 self

转载 作者:IT老高 更新时间:2023-10-28 22:17:16 27 4
gpt4 key购买 nike

我有一个代表对象的类。而且我有一堆方法可以修改这个对象状态,没有明显的返回或明显没有任何返回。在 C# 中,我会将所有这些方法声明为 void 并且看不到任何替代方法。但在 Python 中,我将让所有方法 return self 让自己能够编写出像这样很棒的单行代码:

classname().method1().method2().method3()

这是 Pythonic 还是 Python 可接受的?

最佳答案

这是来自 Guido van Rossum(Python 编程语言的作者)关于此主题的邮件:https://mail.python.org/pipermail/python-dev/2003-October/038855.html

I'd like to explain once more why I'm so adamant that sort() shouldn't return 'self'.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

x.compress().chop(y).sort(z)

which would be the same as

x.compress() x.chop(y) x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

y = x.rstrip("\n").split(":").lower()

There are a few standard library modules that encourage chaining of side-effect calls (pstat comes to mind). There shouldn't be any new ones; pstat slipped through my filter when it was weak.

关于python - 在python中返回 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250990/

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