gpt4 book ai didi

python - 将 self 参数命名为其他名称

转载 作者:太空狗 更新时间:2023-10-30 02:18:01 24 4
gpt4 key购买 nike

在 Python 中,这段代码是有效的:

class A:

def __init__(me):
me.foo = 17

def print_foo(myself):
print(myself.foo)

def set_foo(i, v):
i.foo = v

您可能已经注意到,self 参数在 __init__ 方法中被命名为 memyselfprint_foo 方法中和 iset_foo 方法中。

是否存在将 self 参数命名为 self 以外的名称有用的情况?如果不是,为什么 Python 允许这样做,因为它肯定是一种编写难以阅读和维护的代码的方式,也是混淆的根源?

最佳答案

PEP 8 addresses this pretty clearly:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

虽然记得是 python style guide this is not enforced

However, know when to be inconsistent -- sometimes style guiderecommendations just aren't applicable. When in doubt, use your bestjudgment. Look at other examples and decide what looks best.

有时,like in fractions.py in the standard library ,您可能更清楚地使用类似 a,b 的内容而不是 self,other因为<your specific reasons>

风格指南实际上在上面的引用下方列出了一些您可能会违反惯例的原因:

Some other good reasons to ignore a particular guideline:

  1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
  2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to cleanup someone else's mess (in true XP style).
  3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
  4. When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.

关于python - 将 self 参数命名为其他名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37885330/

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