self is used when creating a class in python, but it doesn't have to be the letter self. It means that it is customary to use self.
And although self is often referred to as oneself, I think this is misleading. As you can see by creating one class and writing a method that returns self, self is ** self at that point **. And that self can be changed intentionally.
sample.py
# -*- coding: utf-8 -*-
class Hoge:
def __init__(self, a):
self.__a = a
def call(self):
print(self.__a)
ins = Hoge(1)
ins.call() # 1
The above code is a general program. However, you can also write like this.
sample2.py
# -*- coding: utf-8 -*-
class Hoge:
def __init__(self, a):
self.__a = a
def call(self):
print(self.__a)
ins = Hoge(1)
Hoge.call(ins) # 1
This is because we are passing the object directly to self. Of course, you can do such strange things.
sample3.py
# -*- coding: utf-8 -*-
class Hoge:
def __init__(self, a):
self.__a = a
def call(self):
print(self.__a)
ins = Hoge(1)
ins2 = Hoge(2)
ins.call() # 1
ins2.call() # 2
Hoge.__init__(ins, 3)
ins.call() # 3
Of course, we don't usually do such strange things! I think it's reasonable, but I personally find it interesting. Isn't it a little fresh for those who write python somehow?
Recommended Posts