python @classmethod 中的“self”指的是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/533300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:19:51  来源:igfitidea点击:

What does 'self' refer to in a @classmethod?

pythonselfclass-method

提问by Yes - that Jake.

I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.

我以为我开始掌握编程的“Python 方式”。类的方法接受 self 作为第一个参数来引用调用该方法的上下文的类的实例。@classmethod 装饰器引用一个方法,其功能与类相关联,但不引用具体实例。

So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?

那么,如果要在没有实例引用的情况下调用该方法,@classmethod(规范的“self”)的第一个参数指的是什么?

回答by SilentGhost

class itself:

类本身

A class method receives the class as implicit first argument, just like an instance method receives the instance.

类方法接收类作为隐式第一个参数,就像实例方法接收实例一样。

class C:
    @classmethod
    def f(cls):
        print(cls.__name__, type(cls))

>>> C.f()
C <class 'type'>

and it's clscanonically, btw

这是cls规范的,顺便说一句

回答by Torsten Marek

The first parameter of a classmethod is named clsby convention and refers to the the class object on which the method it was invoked.

classmethod 的第一个参数按照cls约定命名,指的是调用它的方法所在的类对象。

>>> class A(object):
...     @classmethod
...     def m(cls):
...         print cls is A
...         print issubclass(cls, A)

>>> class B(A): pass
>>> a = A()
>>> a.m()
True
True
>>> b = B()
>>> b.m()
False 
True

回答by boatcoder

Django does some strange stuff with a class method here:

Django 在这里用一个类方法做了一些奇怪的事情:

class BaseFormSet(StrAndUnicode):
    """
    A collection of instances of the same Form class.
    """
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList):
        ...
        self.prefix = prefix or self.get_default_prefix()
        ...

Even though get_default_prefix is declared this way (in the same class):

即使 get_default_prefix 以这种方式声明(在同一个类中):

    @classmethod
    def get_default_prefix(cls):
        return 'form'

回答by Jason Baker

The class object gets passed as the first parameter. For example:

类对象作为第一个参数传递。例如:

class Foo(object):
    @classmethod
    def bar(self):
        return self()

Would return an instance of the Foo class.

将返回 Foo 类的一个实例。

EDIT:

编辑

Note that the last line would be self() not self. self would return the class itself, while self() returns an instance.

请注意,最后一行是 self() 而不是 self。self 将返回类本身,而 self() 返回一个实例。