0
0
Pythonprogramming~5 mins

Self reference in Python

Choose your learning style9 modes available
Introduction
Self reference lets an object or function refer to itself. This helps when you want to work with the current item or repeat actions inside itself.
When you want a method inside a class to access or change the object's own data.
When a function needs to call itself to solve a problem step by step.
When you want to keep track of the current object in a group of objects.
When you want to build structures like linked lists where each part points to itself or others.
Syntax
Python
class ClassName:
    def method(self):
        # use self to access attributes or other methods
        self.attribute = value
        self.other_method()
In Python, 'self' is the name used to refer to the current object inside class methods.
You must always include 'self' as the first parameter in instance methods.
Examples
Here, 'self.name' stores the name for each person object. The greet method uses 'self' to access that name.
Python
class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        print(f"Hello, my name is {self.name}.")
This function calls itself to calculate factorial. This is self reference in functions.
Python
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
Sample Program
This program uses self reference to keep track of the count inside the Counter object. Each call to increment changes the object's own count.
Python
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
        print(f"Count is now {self.count}")

counter = Counter()
counter.increment()
counter.increment()
OutputSuccess
Important Notes
Always remember to use 'self' to access or change attributes inside class methods.
Self reference helps keep data and behavior together in objects.
In recursive functions, self reference means the function calls itself.
Summary
Self reference means an object or function refers to itself.
In Python classes, 'self' is used to access the current object's data and methods.
Self reference is useful for keeping track of data or repeating actions.