The self in Python is used to represent the current instance of the class. Using the self keyword can access the attributes and methods of the class in python because it binds the attributes with the given arguments.
It has to be the first parameter of any function in the class.
Example self in Python
Simple example code uses the words seld and abc instead of self because It doesn’t have to be named self, you can change the name of it.
class Employee:
def __init__(self, name, salary):
self.name = name
self.age = salary
def myfunc(abc):
print("Hello " + abc.name)
p1 = Employee("John", 36)
p1.myfunc()
Output:
![What is self in Python](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2021/09/What-is-self-in-Python.jpg?resize=261%2C132&ssl=1)
Another example
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am {self.name}, and I am {self.age} years old.")
def make_sound(self):
print("Meow")
cat1 = Cat('Andy', 3)
cat1.info()
cat1.make_sound()
Output:
I am Andy, and I am 3 years old.
Meow
Do comment if you have any doubts or suggestions on this Python basic tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.