将自参数命名为els

2024-03-29 07:33:38 发布

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

在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__方法中命名为me,在print_foo方法中命名为{},在{}方法中命名为i。在

有没有一种情况下,将self参数命名为self之外的其他参数是有用的吗?如果不是这样,为什么Python允许这样做,因为这无疑是编写一个难以阅读和维护的代码的方法,而且也是一个混淆的来源?在


Tags: 方法代码self参数fooinitdef来源
3条回答

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 guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best.

有时,像in ^{},使用类似a,b而不是{}的东西可能会更清楚,因为<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 clean up 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.

你的问题的第一部分是:“有没有一种情况下,将self参数命名为self以外的东西是有用的?”我不知道有什么真正有说服力的案例,但即使有人提出了完美的例子,它们也很罕见,我也不会把它们作为这个设计选择的理由:正常使用远比偶尔以非直观的方式使用self重要得多。(请注意,强制使用名称self不会阻止任何人完成任何事情;它只是一个名称。)

那么python为什么允许这样做呢?这里有两个问题:为什么要求在参数中显式列出self(这给了我们选择另一个名称的机会),以及为什么不将self变成关键字,比如在某些其他语言中this。在

为什么它不是一个关键字是非常清楚的:python的设计者总是尽量减少语言中保留字的数量(在引入新语法时,例如使用yield fromfrom ... import、和{})时,尽一切努力重用已经保留的单词。因此,如果某件事可以合理地实现而不是保留字,那就是了。在

一旦确定self不是一个关键字,而是一个特殊的标识符,如何使其特殊?使它突然出现在每个类方法的locals()字典中会引入“魔术”行为,这也是不可取的:“显式优于隐式。”因此,self是通过在方法签名中声明来引入的,唯一特殊的行为是第一个参数绑定到我们调用其方法的对象。这使得通过修饰符支持静态方法和类方法变得很容易,而无需向语言添加特殊语法。(正如Guido的this post所解释的那样,“用纯Python编写一个实现@classmethod或{}的装饰器很简单。”)因此,一旦语言以这种方式设计,就真的没有回头路了。在

self参数实际上只是按照约定命名self,而且这甚至不是一个普遍接受的约定——我还经常看到cls这个被使用。在

术语self在python中并不像Java那样是一个关键字。用户可以选择为它命名任何他们想要的名称-尽管最好选择一个名称并在整个代码中坚持这个名称,但是没有任何东西阻止您在每个方法中为它命名不同的名称。在

相关问题 更多 >