Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
self
self
is the first argument in methods, which name is agreed upon by Python programmers. When an instance executes a method, it automatically passes itself as the first argument. Let's consider the User
class we created earlier as an example:
class User: def __init__(self, name, surname, age): # self=bob, name="Bob", surname="Smith", age=11 self.name = name # bob.name = "Bob" (name argument) self.surname = surname # bob.surname = "Smith" (surname argument) self.age = age # bob.age = 11 (age argument) bob = User("Bob", "Smith", 11) print(bob.name, bob.surname, bob.age)
The __init__
magic method takes the arguments self
, name
, surname
, and age
. In the given example, when we create the bob
instance, these arguments are passed as values.
Let's use the print()
function to examine the passed arguments:
class User: def __init__(self, name, surname, age): print("===== INIT ARGUMENTS =====") print("self:", self) print("name:", name) print("surname:", surname) print("age:", age) self.name = name self.surname = surname self.age = age bob = User("Bob", "Smith", 11) print("===== GLOBAL =====") print("bob:", bob) print("bob.name:", bob.name) print("bob.surname:", bob.surname) print("bob.age:", bob.age)
In the given example, it is evident that the global variable bob
and the self
parameter inside the __init__
method refer to the same instance. This illustrates the convention in Python where methods receive the instance as the first argument, conventionally named self
.
By following this convention, methods have access to the instance attributes and can perform operations or access values specific to that particular instance.
Note
In Python, the
self
parameter serves as the first argument in methods and represents the instance object that calls the method. By convention, the nameself
is used, although it could be any valid variable name. This parameter provides access to the attributes and methods of the instance, allowing the method to interact with and manipulate its own data.
For better understanding, let's create a regular function and name it init
, which will perform the same actions but will be called separately.
class User: pass def init(instance, arg1, arg2, arg3): instance.name = arg1 instance.surname = arg2 instance.age = arg3 bob = User() init(bob, "Bob", "Smith", 11) print(bob.name, bob.surname, bob.age)
The init
function takes the first argument as an instance and then assigns the received arguments to it. Similarly, __init__
works when creating a class, and self
is a necessary element for creating different methods, which we will discuss further.
Дякуємо за ваш відгук!