‘self’ 是什么意思? 在@classmethod 中引用?
我以为我开始掌握“Python 方式”编程了。 类的方法接受 self 作为第一个参数,以引用该方法在其上下文中调用的类的实例。 @classmethod 装饰器引用其功能与该类相关联的方法,但不引用具体实例。
那么,如果要在没有实例引用的情况下调用该方法,那么 @classmethod 的第一个参数(规范上的“self”)指的是什么呢?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类本身:
顺便说一句,它是规范的
cls
class itself:
and it's
cls
canonically, btw按照惯例,类方法的第一个参数被命名为 cls,并引用调用该方法的类对象。
The first parameter of a classmethod is named
cls
by convention and refers to the the class object on which the method it was invoked.类对象作为第一个参数传递。 例如:
将返回 Foo 类的实例。
编辑:
请注意,最后一行是 self() 而不是 self。 self 将返回类本身,而 self() 返回一个实例。
The class object gets passed as the first parameter. For example:
Would return an instance of the Foo class.
EDIT:
Note that the last line would be self() not self. self would return the class itself, while self() returns an instance.
Django 在这里用类方法做了一些奇怪的事情:
即使 get_default_prefix 是这样声明的(在同一个类中):
Django does some strange stuff with a class method here:
Even though get_default_prefix is declared this way (in the same class):