你什么时候在 Python 中使用“self"? [英] When do you use 'self' in Python?

查看:42
本文介绍了你什么时候在 Python 中使用“self"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

更一般地说,我想知道什么时候需要使用 self,不仅用于方法,还用于变量.

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

推荐答案

添加答案,因为 Oskarbi 的不明确.

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

您在以下情况下使用 self:

You use self when:

  1. 定义一个实例方法.当您在实例上调用方法时,它会自动作为第一个参数传递,并且它是调用该方法的实例.
  2. 从实例方法内部引用类或实例属性.使用它来调用方法或访问方法被调用的实例上的名称(变量),从该方法内部.
  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 you want to call a method or access a name (variable) on the instance the method was called on, from inside that method.

不要使用self

  1. 您通常调用实例方法.使用 Oskarbi 的例子,如果你执行 instance = MyClass(),你将 MyClass.my_method 称为 instance.my_method(some_var) 而不是 >instance.my_method(self, some_var).
  2. 您从外部实例方法引用了一个类属性,但在类定义内部.
  3. 您在 staticmethod 中.
  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.

这些不只是什么时候不使用 self.当你应该使用它.

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

这篇关于你什么时候在 Python 中使用“self"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆