Constructor and self Keyword in Python

 

Constructor (__init__ Method)

  • __init__: The constructor method in Python.
  • Automatic Call: Runs automatically when an object is created.
  • Initialize Attributes: Sets up the object's initial values.
Example:

class Example:
    def __init__(self, value):
        self.value = value

self Keyword

  • self: Refers to the current object instance.
  • Access Attributes: Used to access variables and methods inside the class.
  • Always First Parameter: Must be the first parameter in instance methods.

Example:

class Example:
    def __init__(self, value):
        self.value = value  # Using 'self' to set the value

Post a Comment

0 Comments