Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. class / __init__() / self

class / __init__() / self

In Python, classes are defined using the class keyword. __init__() is the initializer method called when an instance is created, and self refers to the instance itself. By convention, self is always the first parameter, but Python passes it automatically — you do not include it when calling the method.

Syntax

class ClassName:
    # Class variable (shared across all instances)
    class_var = value

    def __init__(self, arg):
        # Instance variable (unique to each instance)
        self.variable = arg

    def method(self):
        return self.variable

Special Methods

Special MethodDescription
__init__(self, ...)Initializer called when an instance is created.
__str__(self)Called by str() and print(). Returns a human-readable string representation.
__repr__(self)Called by repr(). Returns a detailed string representation intended for developers.
__del__(self)Destructor called just before the instance is deleted.

Sample Code

# Basic class definition
class Person:
    # Class variable (shared by all instances)
    species = 'Human'
    count = 0

    def __init__(self, name, age):
        # Instance variables
        self.name = name
        self.age  = age
        Person.count += 1  # Update the class variable

    def greet(self):
        return f"Hello! I'm {self.name}, age {self.age}."

    def birthday(self):
        self.age += 1
        return f"{self.name} is now {self.age} years old!"

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

    def __del__(self):
        Person.count -= 1

# Creating instances
p1 = Person('Alice', 30)
p2 = Person('Bob', 25)

print(p1.greet())       # Hello! I'm Alice, age 30.
print(p2.birthday())    # Bob is now 26 years old!
print(Person.count)     # 2 (class variables are accessed via the class name)
print(p1.species)       # Human (also accessible from an instance)

# Checking __str__ and __repr__
print(str(p1))      # Person(name=Alice, age=30)
print(repr(p1))     # Person('Alice', 30)
print(p1)           # Person(name=Alice, age=30) (print() uses __str__)

# Difference between instance variables and class variables
p1.species = 'Earthling'   # Creates an instance variable on p1 (class variable is unchanged)
print(p1.species)           # Earthling
print(p2.species)           # Human (class variable is unchanged)
print(Person.species)       # Human (class variable is unchanged)

# __init__ with a default argument
class Circle:
    PI = 3.14159

    def __init__(self, radius=1.0):
        self.radius = radius

    def area(self):
        return Circle.PI * self.radius ** 2

c1 = Circle(5)
c2 = Circle()       # radius defaults to 1.0
print(c1.area())    # 78.53975
print(c2.area())    # 3.14159

Notes

Class variables are shared across all instances of a class. If you assign a value to a class variable through an instance, Python creates a new instance variable on that instance instead — the class variable itself remains unchanged. When using class variables for shared counters or configuration, always access them via the class name to avoid this pitfall.

Design __str__() to return a human-readable string, and __repr__() to return a detailed string for debugging. Ideally, __repr__() should return a string that eval() can use to recreate the object. When that is not practical, the convention is to use the format <ClassName attribute_info>.

If you find any errors or copyright issues, please .