Answer the question
In order to leave comments, you need to log in
What is self in Python?
It is not at all clear what self is. It is clear that by default it must be written as the first parameter in the description of each method. That is, the definition has already been learned by heart, but it is difficult to understand what it means. It seems that there are no difficulties so far with anything else, only with this. I've been looking for what it is for a long time.
Answer the question
In order to leave comments, you need to log in
Googled it easily.
stackoverflow.com/a/21366809/3307167 - for me the most understandable option.
stackoverflow.com/a/31096552/3307167 - and there are even pictures here, for a better understanding.
An analogue of the word this from other languages.
In Python, "Explicit is better than implicit" so it needs to be so specific.
Refers to a specific instance of a class, not the class as a whole.
self is by no means a reserved word. It's just a variable name.
In class methods, the first parameter of a function is by convention named self, and is a reference to the object of that class itself. But that's just the agreement. You are free to name the parameters whatever you like.
Why is this needed?
Well, there is an object and you want to create / change the field of this object from the method of this very object.
class Human:
def __init__(self):
self.blood = 7000
def add_blood(self, volume):
self.blood += volume
The author of the question, please answer me, the same problem as you, I don’t understand how this self works (((
self is a call to an object,
class Human:
def __init__(self):
self.blood = 7000
self - is a simple call to an object.
x.blood = 7000 - you can assign any other value specifically to this object, for example: x.blood = 6500.
Accordingly, when it is called, it will be changed
, you can not change anything, and if you just write it, it will give the default value.
>>>x.blood
7000
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question