What is ‘self’ in a class?

Think to a class like a box in which you put variables called attributes and functions called methods. You can access to them via the ‘self’ word. Self will be the name of the istance of the class you will create.

Self it’s the ‘future‘ name of the istance that will use the class structure.

Here the class structure contains just name (attribute aka variables into a class). Each istance will have it’s name. To have access to the name => istancename.attribute.

class Man:
    def __init__(self, name):

        self.name = name
    

man1 = Man("john")
print(man1.name)
# output will be 'john'

man2 = Man("Paul")
print(man2.name)
# output will be 'paul'   

# now you have access to the attribute name because a=self and b=self in the 2 istances.

Same for the methods (functions into a class)

class MathShortcuts:
    def __init__(self, x):
        self.x = x
    def double(self):
        return self.x * 2

d1 = MathShortcuts(2)
print(d1.double())
# will be 4
    
d2 = MathShortcuts(3)
print(d2.double())
# will be 6

 

Video Tutorial about class in Python (with self)


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.