Skip to content

What is self in Python | Basics

  • by

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

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading