Understanding python self

What is self

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.

Change yourself

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

Summary

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

Understanding python self
Understanding Python Coroutine
Python
Try to understand Python self
Paiza Python Primer 8: Understanding Classes
Paiza Python Primer 7: Understanding Functions
Full understanding of Python debugging
Python and DB: Understanding DBI cursors
[Python] Understanding the potential_field_planning of Python Robotics
[Road to Intermediate] Understanding Python Properties
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Built-in python
Python comprehension
Python technique
Studying python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Understanding VQ-VAE
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Try python
Python memo
Python iterative
Python2 + word2vec
Python functions
Python tutorial
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Understanding Concatenate
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo
Python memorandum
Python # sort
ufo-> python