你什么时候使用“self”?在Python中?

发布于 2024-12-09 13:34:55 字数 97 浏览 1 评论 0原文

在 Python 中引用成员函数(在同一模块内)时,是否应该使用 self ?

更一般地说,我想知道什么时候需要使用 self ,不仅对于方法而且对于变量也是如此。

Are you supposed to use self when referencing a member function in Python (within the same module)?

More generally, I was wondering when it is required to use self, not just for methods but for variables as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

揽月 2024-12-16 13:34:55

添加答案是因为奥斯卡比的答案不明确。

在以下情况下使用 self

  1. 定义实例方法。当您在实例上调用方法时,它会作为第一个参数自动传递,并且它是调用该方法的实例。
  2. 从实例方法内部引用类或实例属性。当您想要从该方法内部调用方法或访问调用该方法的实例上的名称(变量)时,请使用它。

时,使用self

  1. 当您正常调用实例方法 。使用 Oskarbi 的示例,如果您执行 instance = MyClass(),则将 MyClass.my_method 调用为 instance.my_method(some_var),而不是 instance.my_method(self, some_var)
  2. 您可以从实例方法外部但在类定义内部引用类属性。
  3. 您位于 staticmethod 中。

这些不该做的事情只是何时不使用 self 的示例。 dos 是您应该使用它的时间。

Adding an answer because Oskarbi's isn't explicit.

You use self when:

  1. Defining an instance method. It is passed automatically as the first parameter when you call a method on an instance, and it is the instance on which the method was called.
  2. Referencing a class or instance attribute from inside an instance method. Use it when you want to call a method or access a name (variable) on the instance the method was called on, from inside that method.

You don't use self when

  1. You call an instance method normally. Using Oskarbi's example, if you do instance = MyClass(), you call MyClass.my_method as instance.my_method(some_var) not as instance.my_method(self, some_var).
  2. You reference a class attribute from outside an instance method but inside the class definition.
  3. You're inside a staticmethod.

These don'ts are just examples of when not to use self. The dos are when you should use it.

余厌 2024-12-16 13:34:55

使用self从其他实例方法引用实例变量和方法。还将 self 作为实例方法定义中的第一个参数。

一个例子:

class MyClass(object):

    my_var = None

    def my_method(self, my_var):
         self.my_var = my_var
         self.my_other_method()

    def my_other_method(self):
         # do something...

Use self to refer to instance variables and methods from other instance methods. Also put self as the first parameter in the definition of instance methods.

An example:

class MyClass(object):

    my_var = None

    def my_method(self, my_var):
         self.my_var = my_var
         self.my_other_method()

    def my_other_method(self):
         # do something...
懵少女 2024-12-16 13:34:55
  1. self 这个名字没有什么“特别”之处。这是 Pythonistas 惯用的名称,用于指示该参数应包含的内容。

  2. 当您在实例上调用实例方法时,Python 运行时将传递一个“self”值,无论您是否有意提供它。这通常会导致易于诊断/理解的错误(因为该函数将使用错误数量的参数来调用),但使用 *args 可能会导致更奇怪的类型错误。

  3. 当您在实例上调用实例方法时,该参数会隐式传递。它包含您调用该方法的实例。因此,您不会在函数调用中提及 self ,因为 (a) 如上所述,这没有任何意义(作用域中没有 self ,一般来说,self 不是关键字或特殊名称或任何东西); (b) 您已经指定要使用的实例(通过编写 my_instance.)。

  4. 当然,您可以通过从类访问实例方法来显式调用它。在这种情况下,您需要将实例作为第一个参数显式传递。一般来说,您不想这样做。而且您尤其不想编写考虑第一个参数是通过这种方式显式传递的其他参数的可能性的代码。这类似于在 C++ 中检查 if (this == null):你不这样做,因为 如果它可能意味着任何内容,那么调用代码是 <强>错,即使在法律上不合法,在道德上也是如此。 (至少在 Python 中,您不会遇到未定义行为的问题,但这在道德上仍然是错误的。)

  5. 在实例方法中,因为self是一个参数,它已被分配给实例作为value,您可以编写 self.whatever 来访问实例的属性。与其他一些“隐式 this” 样式语言不同,属性名称隐式“在范围内”。

  6. self 没有其他用例,因为它也不是一个特殊的名称,并且这是命名约定所解决的一个特定目的。如果您需要从另一个模块访问“变量”(实际上是一个属性),您可以使用模块名称。如果您想从当前模块访问其中一个,则不需要前缀,或者实际上是可能的。 (好吧,您可以globals() 返回的 dict 中显式查找它,但请不要这样做。)

  1. There is nothing 'special' about the name self. It is the name preferred by convention by Pythonistas, to indicate what that parameter is expected to contain.

  2. The Python runtime will pass a 'self' value when you call an instance method on an instance, whether you deliberately provide for it or not. This will usually result in an easily diagnosed/understood error (since the function will get called with the wrong number of parameters), but the use of *args can lead to rather more strange type errors.

  3. The parameter is passed implicitly when you call an instance method on an instance. It contains the instance upon which you call the method. So you don't mention self in the function call because (a) as noted above, that wouldn't make any sense (there isn't a self in scope, in general, and self is not a keyword or special name or anything); (b) you've already indicated the instance to use (by writing my_instance.).

  4. You can, of course, explicitly call an instance method by accessing it from the class. In this case, you'll need to pass the instance explicitly as the first parameter. You generally speaking don't want to do this. And you especially don't want to write code that considers the possibility that the first parameter is something else that's been explicitly passed in this way. This is akin to checking if (this == null) in C++: you don't do it, because if it could possibly mean anything, then the calling code is wrong, morally if not legally. (At least in Python you won't have problems with undefined behaviour, but it's still morally wrong.)

  5. Within the instance method, since self is a parameter which has been assigned the instance as a value, you can write self.whatever to access attributes of the instance. Unlike in some other 'implicit this' style languages, the attribute names are not implicitly "in scope".

  6. There are no other use cases for self, since again it's not a special name, and that is the one specific purpose that the naming convention addresses. If you needed to access a 'variable' (really an attribute) from another module, you would use the module name. If you wanted to access one from the current module, no prefix is needed, or really possible for that matter. (Well, you could explicitly look it up in the dict returned by globals(), but please don't do that.)

饭团 2024-12-16 13:34:55

对于实例变量和方法来说,任何时候都必须使用 self 。

For instance variable and for methods it is mandatory to use self anytime.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文