Python self Parameter

🐍 Python self Parameter

The self parameter is a convention in Python used in object-oriented programming.
It represents the instance of the class and allows access to attributes and methods of that object.


🔍 Key Points About self

  1. self refers to the current object.

  2. Must be the first parameter in instance methods, including __init__().

  3. Not a keyword, you can technically use other names, but self is standard.

  4. Required to access instance variables and methods.


✅ Basic Example

class Person:
def __init__(self, name, age):
self.name = name # instance variable
self.age = age
def display(self):
print(f”Name: {self.name}, Age: {self.age}“)

p = Person(“Vipul”, 25)
p.display()

Explanation:

  • self.name and self.age are attributes of the object p.

  • Without self, Python wouldn’t know which object’s variables to use.


🧠 Why self is Important

class Person:
def __init__(name, age): # missing self
name = name
age = age
p = Person(“Vipul”, 25)

❌ This won’t work because Python doesn’t know these are instance attributes.
You must use self:

self.name = name
self.age = age

🔄 Accessing Methods via self

class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius

def display_area(self):
print(“Area:”, self.area()) # calling method using self

c = Circle(5)
c.display_area()


⚡ Calling Attributes Between Methods

class Car:
def __init__(self, brand):
self.brand = brand
def show_brand(self):
print(“Brand is”, self.brand)

def rename_brand(self, new_name):
self.brand = new_name

car = Car(“BMW”)
car.show_brand() # BMW
car.rename_brand(“Audi”)
car.show_brand() # Audi


🧩 self vs Class Variables

class Laptop:
brand = "Dell" # class variable
def __init__(self, ram):
self.ram = ram # instance variable

l1 = Laptop(“8GB”)
l2 = Laptop(“16GB”)

print(l1.brand, l1.ram)
print(l2.brand, l2.ram)

  • self.ram is unique for each object.

  • brand is shared among all objects.


⚠ Notes

  1. self is not passed manually; Python passes it automatically.

    obj.method() # Python passes obj as self
  2. Can technically use another name, e.g., this, but do not — follow convention.


✅ Summary

Feature Description
self Refers to the current object
Required in All instance methods, including __init__()
Purpose Access instance attributes & methods
Convention Always use self

🧪 Practice Tasks

  • Create a class Employee and use self to assign name and salary.

  • Add methods to display and update the salary using self.

  • Create two objects and test if their attributes are independent.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *