在Python中定义一个引用self而不是“self”的类方法有用吗?

2024-06-08 23:07:28 发布

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

我在自学Python,我在Dive into Pythonsection 5.3中看到了以下内容:

By convention, the first argument of any Python class method (the reference to the current instance) is called self. This argument fills the role of the reserved word this in C++ or Java, but self is not a reserved word in Python, merely a naming convention. Nonetheless, please don't call it anything but self; this is a very strong convention.

考虑到self是一个Python关键字,我想它有时也可以用来使用其他东西。有这种情况吗?如果不是,为什么它是一个关键字?在


Tags: oftheinselfis关键字thisargument
3条回答

不,除非你想让其他在你写代码后看你代码的程序员感到困惑。self不是关键字,因为它是标识符。It可能是一个关键字,事实上它不是一个是一个设计决策。在

我见过的唯一一种情况是在类定义之外定义一个函数,然后将其分配给该类,例如:

class Foo(object):
    def bar(self):
        # Do something with 'self'

def baz(inst):
    return inst.bar()

Foo.baz = baz

在本例中,self使用起来有点奇怪,因为该函数可以应用于许多类。我经常看到inst或{}来代替。在

作为一个侧面观察,请注意Pilgrim在这里犯了一个常见的术语误用:一个类方法与一个实例方法是完全不同的,这正是他在这里所说的。正如wikipedia所说,“方法是一个只与类(在这种情况下称为类方法或静态方法)或对象(在这种情况下它是实例方法)相关联的子例程。”。Python的内置函数包括一个staticmethod类型,用于生成静态方法,以及一个用于生成类方法的classmethod类型,它们通常用作装饰器;如果不使用这两个类型,则类主体中的def将生成一个实例方法。E、 g.:

>>> class X(object):
...   def noclass(self): print self
...   @classmethod
...   def withclass(cls): print cls
... 
>>> x = X()
>>> x.noclass()
<__main__.X object at 0x698d0>
>>> x.withclass()
<class '__main__.X'>
>>> 

如您所见,实例方法noclass获取实例作为其参数,而类方法withclass获得类。在

因此,使用self作为类方法的第一个参数的名称是非常令人困惑和误导的:本例中的约定是使用cls,如我上面的例子所示。虽然这只是一个约定,但没有真正好的理由来违反它——比方说,如果变量的目的是计数狗,那么命名一个变量number_of_cats就没有什么理由了!-)在

相关问题 更多 >