Для чего нужен self в python
Перейти к содержимому

Для чего нужен self в python

  • автор:

Classes in Python

Classes and objects are the two main aspecs of object oriented programming. A class creates a new type where objects are instances of the class.

Objects can store data using ordinary variables that belong to the object. Variables that belong to an object or class are called as fields. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. This terminology is important because it helps us to differentiate between functions and variables which are separate by itself and those which belong to a class or object. Collectively, the fields and methods can be referred to as the attributes of that class.

1 The self

Class methods have only one specific difference from ordinary functions — they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self.

2 The init method

There are many method names which have special significance in Python classes. We will see the significance of the __init__ method now. The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

3 accees control

We see from last example name attribute can be easily modified. We can add two underline __name to control access.

4 Class variables and Object variables

There are two types of fields — which are classified depending on whether the class or the object owns the variables respectively.

Class variables are shared in the sense that they are accessed by all objects (instances) of that class. There is only copy of the class variable and when any one object makes a change to a class variable, the change is reflected in all the other instances as well.

Object variables are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the samen name in a different instance of the same class. An example will make this easy to understand.

5 Inheritance

One of the major benefits of object oriented programming is reuse of code and one of the ways this is achieved is through the inheritance mechanism. Inheritance can be best imagined as implementing a type and subtype relationship between classes.

В чем суть self?

Обычно класс создают для того, чтобы потом создать некоторое количество экземпляров этого класса.
При написании класса нужно как-то указать, что какие-то манипуляции нужно производить именно над конкретными экземплярами, а не над самим классом.

Для этого в функциях (кроме некоторых исключений) первым аргументом пишут имя (по традиции это как раз слово «self», хотя на самом деле там можно указать любое корректное имя). В результате, когда в функции интерпретатор видит имя self, он понимает, что речь идёт именно об одном конкретном объекте класса.

Для чего нужен self в python

self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

The reason you need to use self. is because Python does not use the @ 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.

Python's self

Sign in to your Python Morsels account to save your screencast settings.

Don’t have an account yet? Sign up here.

When you define a class in Python, you’ll see self everywhere. What is self and why is it everywhere?

A Python class with self in each method

The below Point has three methods: a __init__ method, an is_origin method, and a move_to method.

We can make an instance of this class, by calling it. We can access attributes and can call methods on this class instance:

Do we need that self argument?

Each of the methods in our Point class accepts self as its first argument. What do you think will happen, if we delete that self argument?

Now when we call the Point class to make a new Point object, we’ll see an error:

The error says __init__ (our initializer method) takes three positional arguments, but four were given. We only passed three arguments into our Point class; it got four arguments because self was passed in as the first argument (before the three we specified).

So whether you like it or not, the first argument to every one of your methods is going to be self , which means we need to capture this self thing that’s passed in as the first argument.

What is self ?

So what is self ?

Let’s temporarily change our is_origin method here to return the id of self :

Python’s id function returns a number representing the memory location of a particular object.

If we call the is_origin function, we get a number.

If we look at the id of the p variable we made, we’re going to get the same number:

That variable p points to a Point object (remember variables are pointers in Python). That self variable in our method call points to the same exact object.

So self is really just a variable that points to the instance of our class that we’re currently working with.

But what does self mean? Could we rename it?

What if we take self everywhere in the code and change it to this ?

Would our code still work?

If we make a new Point object again, we’ll see that we everything works as it did before: we can still access attributes and we can still call methods:

From Python’s perspective, it doesn’t actually matter, what you call self . You just have to accept that the instance of your class will be passed in as the first argument. The self variable is just a very strong convention, you should call it self (otherwise other Python programmers will be confused when reading your code) but you’re allowed to call it something else.

self is the first method of every Python class

When Python calls a method in your class, it will pass in the actual instance of that class that you’re working with as the first argument. Some programming languages use the word this to represent that instance, but in Python we use the word self .

When you define a class in Python, every method that you define, must accept that instance as its first argument (called self by convention).

The self variable points to the instance of the class that you’re working with.

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

Series: Classes

Classes are a way to bundle functionality and state together. The terms «type» and «class» are interchangeable: list , dict , tuple , int , str , set , and bool are all classes.

You’ll certainly use quite a few classes in Python (remember types are classes) but you may not need to create your own often.

To track your progress on this Python Morsels topic trail, sign in or sign up.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *