4
4
4442015-10-06 23:27:25
Python
444, 2015-10-06 23:27:25

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

7 answer(s)
D
Defman21, 2015-10-06
@444

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.

K
Konstantin Dovnar, 2015-10-06
@SolidlSnake

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.

A
Alexander, 2017-11-14
@Survtur

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

V
Vovanchick, 2019-02-11
@Vovanchick

And still nothing is clear

M
Mori_sad, 2020-05-02
@Mori_sad

The author of the question, please answer me, the same problem as you, I don’t understand how this self works (((

Y
Yaroslav, 2021-11-28
@Yareeek192

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 question

Ask a Question

731 491 924 answers to any question