考虑此示例:
class MyClass:
def func(self, name):
self.name = name
我知道 self
是指 myclass
的特定实例。但是,为什么 func
明确将 self
作为参数?为什么我们需要在方法的代码中使用 self
?其他一些语言使这种隐式或使用特殊语法。
对于A 语言 - agnostic 考虑设计决定的考虑指针强制性显式?。
关闭调试问题其中op省略了 self
一种方法的参数并获得了 type> type> typeerror
,使用 typeError:typeError:method()取1个位置参数,但给出了2个,但 。如果在该方法的正文中省略了 self。我可以在类中调用功能吗?。
Consider this example:
class MyClass:
def func(self, name):
self.name = name
I know that self
refers to the specific instance of MyClass
. But why must func
explicitly include self
as a parameter? Why do we need to use self
in the method's code? Some other languages make this implicit, or use special syntax instead.
For a language-agnostic consideration of the design decision, see What is the advantage of having this/self pointer mandatory explicit?.
To close debugging questions where OP omitted a self
parameter for a method and got a TypeError
, use TypeError: method() takes 1 positional argument but 2 were given instead. If OP omitted self.
in the body of the method and got a NameError
, consider How can I call a function within a class?.
发布评论
评论(27)
您需要使用
self。
的原因是因为Python不使用特殊语法来参考实例属性。 Python决定以一种使该方法属于 自动传递的实例的方式,而不是自动传递的方法:方法的第一个参数是实例被称为。这使方法与函数完全相同,并将实际名称留给您(尽管self
是惯例,当您使用其他内容时,人们通常会向您皱眉。)> self
对代码不是特别的,它只是另一个对象。Python本可以做其他事情以将正常名称与属性区分开 - 像Ruby一样的特殊语法,或者需要C ++和Java之类的声明,或者可能更不同 - 但事实并非如此。 Python的全部是使事物明确的,使它显而易见,尽管它并不完全在任何地方做到这一点,但它确实做到了,例如属性。这就是为什么分配给实例属性需要知道要分配的实例的原因,这就是为什么它需要
self。
。The reason you need to use
self.
is because Python does not use special syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (althoughself
is the convention, and people will generally frown at you when you use something else.)self
is not special to the code, it's just another object.Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs
self.
.假设您有一个类
classa
,其中包含方法methoda
定义为:和
objecta
是此类的实例。现在,当调用
objecta.methoda(arg1,arg2)
时,python内部将其转换为:self
变量涉及对象本身。Let's say you have a class
ClassA
which contains a methodmethodA
defined as:and
objectA
is an instance of this class.Now when
objectA.methodA(arg1, arg2)
is called, python internally converts it for you as:The
self
variable refers to the object itself.让我们上一个简单的向量类:
我们想拥有一种计算长度的方法。如果我们想在班上定义它会是什么样?
将其定义为全局方法/函数时,它应该是什么样的?
因此整个结构保持不变。我怎么能利用这个?如果我们假设我们没有为我们的
vector
类写length
方法,那么我们可以做到这一点:这是因为
length_global的第一个参数
,可以作为self
参数重复使用length_new
。没有明确的self
,这将是不可能的。理解对明确
self
的需求的另一种方法是查看python添加一些句法糖。当您牢记时,基本上,像内部转换为
内部的呼叫很容易看到
self
适合所在的位置。您实际上并未在Python中编写实例方法。您写的是类方法,必须将实例作为第一个参数。因此,您必须明确将实例参数放置在某个地方。Let’s take a simple vector class:
We want to have a method which calculates the length. What would it look like if we wanted to define it inside the class?
What should it look like when we were to define it as a global method/function?
So the whole structure stays the same. How can me make use of this? If we assume for a moment that we hadn’t written a
length
method for ourVector
class, we could do this:This works because the first parameter of
length_global
, can be re-used as theself
parameter inlength_new
. This would not be possible without an explicitself
.Another way of understanding the need for the explicit
self
is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call likeis internally transformed to
it is easy to see where the
self
fits in. You don't actually write instance methods in Python; what you write is class methods which must take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.实例化对象时,对象本身将传递到
self
参数中。因此,对象的数据绑定到对象。以下是一个人想如何可视化每个对象数据可能看起来的示例。注意
self
如何替换为对象的名称。我并不是说下面的示例图是完全准确的,但是希望它可以帮助一个人可视化self
的使用。将对象传递到
self
parameter中,以便对象可以保持保持其自己的数据。尽管这可能不是完全准确的,但请考虑实例化的过程(创建和分配内部值)这样的对象:当制作对象时,对象将类用作其模板(对象的)自己的数据和方法。如果不将对象自己的变量名称传递到
self
参数中,则类中的属性和方法将是一个常规模板,并且不会引用(属于)对象。因此,通过将对象的名称传递到self
参数中,这意味着,如果从一个类实例化了100个对象,那么100个对象中的每个对象都可以跟踪其(每个对象)自己的数据和方法。摘要:类是一般的(不是超特定的)模板,一个新创建的对象可以将其自己的特定数据传递到(不一定会影响可以从同一类创建的对象的情况下必然),允许使用较少的复制代码,其目的是创建许多具有相同模式的对象。
self
用于指定A 特定对象的数据应使用而不是其他数据。请参阅下面的插图:
When objects are instantiated, the object itself is passed into the
self
parameter.Because of this, the object’s data is bound to the object. Below is an example of how one might like to visualize what each object’s data might look. Notice how
self
is replaced with the object's name. I'm not saying this example diagram below is wholly accurate, but it will hopefully help one visualize the use ofself
.The Object is passed into the
self
parameter so that the object can keep hold of its own data.Although this may not be wholly accurate, think of the process of instantiating (creating and assigning internal values) an object like this: When an object is made, the object uses the class as a template for its (the object's) own data and methods. Without passing the object's own variable name into the
self
parameter, the attributes and methods in the class would remain a general template and would not be referenced to (belong to) the object. So, by passing the object's name into theself
parameter, it means that if 100 objects are instantiated from the one class, each of the 100 objects can keep track of its (each object's) own data and methods.Summary: Classes are general (not ultra-specific) templates that a newly created object can pass its own specific data into (without necessarily affecting the rest of the objects that could be created from the same class), allowing for less copy-pasted code that serves the purpose of creating many objects that have the same patterns.
self
is for specifying that a specific object's data should be used instead of some other data.See the illustration below:
我喜欢这个示例:
I like this example:
我将用代码证明不使用类:
类是一种避免一直在“状态”中传递的方法(以及其他不错的事情,例如初始化,类构图,很少需要元类,并支持覆盖运营商的自定义方法。
现在,让我们使用内置的Python类机械演示上述代码,以说明基本上是同一件事。
[从重复的封闭问题中迁移了我的答案]
I will demonstrate with code that does not use classes:
Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).
Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.
[migrated my answer from duplicate closed question]
以下摘录来自 python关于self 的文档:
有关更多信息,请参见 python文档教程。
The following excerpts are from the Python documentation about self:
For more information, see the Python documentation tutorial on classes.
除了所有已经说明的其他原因外,它还可以更轻松地访问覆盖方法。您可以调用
class.some_method(inst)
。一个有用的示例:
As well as all the other reasons already stated, it allows for easier access to overridden methods; you can call
Class.some_method(inst)
.An example of where it’s useful:
它的使用类似于使用
此
在Java中的关键字,即为当前对象提供引用。Its use is similar to the use of
this
keyword in Java, i.e. to give a reference to the current object.与Java或C ++不同,Python不是为面向对象的编程而构建的语言。
首先,方法属于整个类( static方法)或类(对象方法)的对象(实例)。
在python中调用静态方法时,只需写入其中带有常规参数的方法。
但是,需要您制作对象的对象(IE,实例)方法(即在这种情况下是一种动物),需要
self
参数。self
方法也用于参考类中的变量字段。在这种情况下,
self
指的是整个类 的动物名称变量。请记住:如果您在方法中有一个新的变量创建(称为局部变量),则self
将无法使用。该变量仅在该方法运行时存在。要定义字段(整个类的变量),您必须在类方法之外定义它们。如果您不了解我所说的话,那么Google“面向对象的编程”。一旦理解这一点,您甚至都不需要问这个问题:)。
Python is not a language built for Object Oriented Programming, unlike Java or C++.
First off, methods belong to either an entire class (static method) or an object (instance) of the class (object method).
When calling a static method in Python, one simply writes a method with regular arguments inside it.
However, an object (i.e., instance) method, which requires you to make an object (i.e. instance, an Animal in this case), needs the
self
argument.The
self
method is also used to refer to a variable field within the class.In this case,
self
is referring to the animalName variable of the entire class. REMEMBER: If you have a new variable created within a method (called a local variable),self
will not work. That variable exists only while that method is running. For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods.If you don't understand a single word of what I am saying, then Google "Object Oriented Programming." Once you understand this, you won't even need to ask that question :).
首先,自我是一个传统的名称,您可以将其他任何东西(连贯)代替。
它指的是对象本身,因此,当您使用该对象时,您会声明.NAME和.AGE是您将要创建的学生对象的属性(注意,而不是学生班的)。
代码在这里
First of all, self is a conventional name, you could put anything else (being coherent) in its stead.
It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.
Code is here
self
是对象本身的对象引用,因此它们是相同的。在对象本身的上下文中,未调用Python方法。
python中的self
可用于处理自定义对象模型之类的东西。self
is an object reference to the object itself, therefore, they are same.Python methods are not called in the context of the object itself.
self
in Python may be used to deal with custom object models or something.在那里遵循Python Zen“明确胜于隐式”。这确实是对您的班级对象的参考。例如,在Java和PHP中,称为
this
。如果
user_type_name
是模型上的字段,则可以通过self.user_type_name
访问它。It’s there to follow the Python zen “explicit is better than implicit”. It’s indeed a reference to your class object. In Java and PHP, for example, it's called
this
.If
user_type_name
is a field on your model you access it byself.user_type_name
.我很惊讶没有人提出卢阿。 LUA还使用“自我”变量,但是可以省略但仍使用。 C ++对“ this”做同样的事情。我没有任何理由必须在每个功能中声明“自我”,但是您仍然应该能够像使用LUA和C ++一样使用它。对于一种以简短的态度而自豪的语言是奇怪的是,它要求您声明自我变量。
I'm surprised nobody has brought up Lua. Lua also uses the 'self' variable however it can be omitted but still used. C++ does the same with 'this'. I don't see any reason to have to declare 'self' in each function but you should still be able to use it just like you can with lua and C++. For a language that prides itself on being brief it's odd that it requires you to declare the self variable.
请查看以下示例,该示例清楚地说明了
self
self
的目的,以区分实例。来源: python中的自我变量a>
Take a look at the following example, which clearly explains the purpose of
self
self
is used/needed to distinguish between instances.Source: self variable in python explained - Pythontips
常规称为
self
的参数的使用并不那么难以理解,为什么它是必要的?还是为什么明确提及它?我想,对于大多数查找这个问题的用户来说,这是一个更大的问题,或者如果不是这样,他们肯定会有同样的问题,因为他们继续学习python。我建议他们阅读这对博客:1 :使用自我解释
请注意,这不是关键字。
2:我们为什么要这样做和这样为什么我们不能像Java这样的参数将其消除,而是具有关键字
我想添加的另一件事是,可选的
self
参数允许我在一个内部声明静态方法类,不写self
。代码示例:
PS :这仅在Python 3.x中起作用。
在以前的版本中,您必须明确添加
@StaticMethod
decorator,否则self
参数是必不可少的。The use of the argument, conventionally called
self
isn't as hard to understand, as is why is it necessary? Or as to why explicitly mention it? That, I suppose, is a bigger question for most users who look up this question, or if it is not, they will certainly have the same question as they move forward learning python. I recommend them to read these couple of blogs:1: Use of self explained
Note that it is not a keyword.
2: Why do we have it this way and why can we not eliminate it as an argument, like Java, and have a keyword instead
Another thing I would like to add is, an optional
self
argument allows me to declare static methods inside a class, by not writingself
.Code examples:
PS:This works only in Python 3.x.
In previous versions, you have to explicitly add
@staticmethod
decorator, otherwiseself
argument is obligatory.是因为根据Python设计的方式,替代方案几乎无效。 python旨在允许在隐式
this
(a-la java/c ++)或explicit@
(a-la ruby)的上下文中定义方法或函数。工作。让我们以python约定的明确方法为例:现在
fubar
函数无法使用,因为它假定self
是一个全局变量(并且在中Frob
)。替代方法是用替换的全局范围执行方法(其中self
是对象)。隐式方法是
这意味着
myx
将被解释为fubar
中的本地变量(以及frob
)。这里的替代方案是用替换的本地范围执行方法,该范围在呼叫之间保留,但这将消除方法局部变量的正当性。但是,当前情况很好地效果很好:
在这里称为方法
frob
将接收通过self
参数调用的对象,fubar
fubar 仍然可以将对象称为参数,并且可以使用相同的工作( IS 与c.frob
我认为)。Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit
this
(a-la Java/C++) or explicit@
(a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:Now the
fubar
function wouldn't work since it would assume thatself
is a global variable (and infrob
as well). The alternative would be to execute method's with a replaced global scope (whereself
is the object).The implicit approach would be
This would mean that
myX
would be interpreted as a local variable infubar
(and infrob
as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.However the current situation works out well:
here when called as a method
frob
will receive the object on which it's called via theself
parameter, andfubar
can still be called with an object as parameter and work the same (it is the same asC.frob
I think).在
__ Init __
方法中,自我指的是新创建的对象;在其他类方法中,它是指调用方法的实例。self as hif as 只是惯例 ,请按照自己的意愿称呼它!但是在使用它时,例如要删除对象,您必须使用相同的名称:
__ del __(var)
,其中var
在__ init __ Init __( var,[...])
您也应该查看
cls
,以使 更大的图片 。此 POST 可能会有所帮助。In the
__init__
method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name:
__del__(var)
, wherevar
was used in the__init__(var,[...])
You should take a look at
cls
too, to have the bigger picture. This post could be helpful.自我就像当前对象名称或类的实例一样。
self is acting as like current object name or instance of class .
“ self”关键字包含类的参考,如果您想使用或不使用它,则可以通过它,但如果您注意到,每当您在Python中创建新方法时,Python都会自动为您编写自关键字。如果您做一些R& d,您会注意到,如果您在班级中创建两个方法并尝试在另一个中调用一个方法,则除非添加自我(班级的引用),否则它将无法识别方法。
下面的代码抛出了无法解决的参考错误。
现在让我们立即查看下面的示例
,当您创建类Testa的对象时,您可以使用类似的类对象来调用方法m1(),因为方法m1()已包含自关键字
,但是如果您要调用方法m2(),因为没有自我参考,因此您可以使用以下类似的类名来直接调用M2(),
但要练习以自我关键字来依靠其他好处,因为它还有其他好处,例如在内部创建全局变量等。
"self" keyword holds the reference of class and it is upto you if you want to use it or not but if you notice, whenever you create a new method in python, python automatically write self keyword for you. If you do some R&D, you will notice that if you create say two methods in a class and try to call one inside another, it does not recognize method unless you add self (reference of class).
Below code throws unresolvable reference error.
Now let see below example
Now when you create object of class testA, you can call method m1() using class object like this as method m1() has included self keyword
But if you want to call method m2(), because is has no self reference so you can call m2() directly using class name like below
But keep in practice to live with self keyword as there are other benefits too of it like creating global variable inside and so on.
self
是不可避免的。只有一个问题应该
self
是隐式或明确的。guido van rossum
解决了这个问题://neopythonic.blogspot.com/2008/10/why-explitic-self-self-has-to-stay.html“ rel =“ nofollow noreferrer”>self
必须保持。那么,
self
live的何处?如果我们只坚持功能编程,我们将不需要
self
。输入 python oop 后,我们在那里找到
self
。这是典型的用例
类C
与方法m1
此程序将输出:
So
self
保留类实例的内存地址。self
的目的是保留实例方法的参考参考。注意,类方法有三种不同类型:
self
is inevitable.There was just a question should
self
be implicit or explicit.Guido van Rossum
resolved this question sayingself
has to stay.So where the
self
live?If we would just stick to functional programming we would not need
self
.Once we enter the Python OOP we find
self
there.Here is the typical use case
class C
with the methodm1
This program will output:
So
self
holds the memory address of the class instance.The purpose of
self
would be to hold the reference for instance methods and for us to have explicit access to that reference.Note there are three different types of class methods:
“自我”一词是指班级的实例
The word 'self' refers to instance of a class
这是对类实例对象的明确引用。
it's an explicit reference to the class instance object.
来自 docs ,,
在此之前,相关片段,
x = myClass()
from the docs,
preceding this the related snippet,
x = MyClass()
我在这个班级的人中的小2美分
,我们在这里定义了 init 方法,在这里要注意的是 self 和实例变量的记忆位置 p 是相同的
< __ main __。在0x106a78fd0>
上的人对象,如上所述,self和实例变量都是同一对象。
my little 2 cents
In this class Person, we defined out init method with the self and interesting thing to notice here is the memory location of both the self and instance variable p is same
<__main__.Person object at 0x106a78fd0>
so as explained in above, both self and instance variable are same object.
使用
self
是 Python的设计决定,从语言设计的角度来看,并非严格强制强制强制,以使实例对象明确并区分实例变量与局部变量。您可以想到self
始终在那里隐含的替代方案,因为Guido的Blogpost回应了:这违背了Python的咒语“显式比隐含更好”。或使用特殊的语法来参考ruby中的实例变量。但是,Python试图将语法字符保持在最低限度(如今,它正在添加更多语法,例如sistizitment表达式和类型提示)。这在功能上与隐式
self
相同,除非您不将self
像隐藏的变量一样。另一个替代方法是C ++样式语法,使用隐式
此
和明确的类似数据级的声明(相对较新):此
仅用于从实例变量中删除本地变量。如果没有混淆,则使用“类范围”n
。我认为这比在任何地方使用显式self
更干净,但是您需要跟踪什么和ISN' t实例状态。Using
self
is a design decision by python, not strictly mandatory from a language design point of view, to make explicit the instance object and distinguish instance variables from local variables. You could conceive of an alternative whereself
is always implicitly there, as Guido's blogpost responds to:This goes against python's mantra of "explicit is better than implicit". Or use special syntax to refer to instance variables as in Ruby. However Python tries to keep syntax characters to a minimum (nowadays it is adding more syntax, like assignment expressions and type hinting). This is functionally the same as implicit
self
, except you don't treatself
like a hidden variable.Another alternative is C++ style syntax, using implicit
this
and explicit dataclass-like declarations (which are relatively new):this
is only used to disambiguate the local variable from the instance variable. If there is no confusion, the "class scope"n
is used. I think this is cleaner than using explicitself
everywhere, but you need to keep track of what is and isn't instance state.我至少要说python,可以将自我参数视为占位符。
看看这一点:
在这种情况下,自我,许多其他人被用作说出名称值的方法。但是,在那之后,我们使用P1将其分配给我们使用的类。然后,当我们打印它时,我们使用相同的P1关键字。
希望这对Python有帮助!
I would say for Python at least, the self parameter can be thought of as a placeholder.
Take a look at this:
Self in this case and a lot of others was used as a method to say store the name value. However, after that, we use the p1 to assign it to the class we're using. Then when we print it we use the same p1 keyword.
Hope this helps for Python!