What is self in Python | Basics

The self in Python is used to represent the current instance of the class. Using 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

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 and suggestions on this Python basic tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.