Python __init__ and self Explained: Classes for Beginners
To initialize a class in Python, define __init__(self, ...) inside it: Python calls it automatically when you create an object, and self is the new object, so self.name = name stores data on it. A class is a blueprint that bundles data and the functions that work on that data. Each instance has its own attributes and can use the methods defined by the class. The bank-account example uses __init__, self, class variables and inheritance. The examples below show the output and the shared-state mistakes to watch for in Python 3.
On this page▾
| Question | Short answer |
|---|---|
What does __init__ do? |
Runs automatically when an instance is created; receives the arguments given to the class |
What is self? |
The instance, passed in implicitly as the first argument (a naming convention, not a keyword) |
Is __init__ a private method? |
No. Python has no truly private members; it is a special method that runs on creation |
| Where do I put a list each object needs? | Inside __init__, not in the class body |
A first class
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough funds")
return
self.balance -= amount
def summary(self):
return f"{self.owner}: {self.balance}"
Nothing happens when this code runs, other than Python learning that Account exists. As the tutorial says, a class definition has to be executed before it has any effect. To get an object, call the class like a function:
a = Account("Mia", 100)
b = Account("Leo")
a.deposit(50)
a.withdraw(500)
a.withdraw(30)
print(a.summary())
print(b.summary())
print(a.balance, b.balance)
Not enough funds
Mia: 120
Leo: 0
120 0
a and b are two separate instances. Each has its own owner and balance, so changing Mia's balance does not touch Leo's. The withdrawal of 500 was refused, and only the 30 went through: 100 + 50 - 30 = 120.
What does init do, and is it private?
When you write Account("Mia", 100), Python creates a new empty object and then calls __init__ on it, passing along your arguments. The tutorial describes __init__ as the special method that runs automatically when an instance is created, and says arguments given to the class are passed to it. Inside it, self.owner = owner attaches a piece of data to this particular object. That is why Leo, created with no second argument, got the default balance of 0.
__init__ is not private. The tutorial says private instance variables that cannot be accessed except from inside an object do not exist in Python; a single leading underscore (_spam) is only a convention for non-public names, and names with two leading underscores and at most one trailing underscore are name-mangled. __init__ ends with two underscores, so it is neither: it is an ordinary, public special method.
What is self in Python?
Look at a.deposit(50). The method is defined with two parameters, self and amount, yet you passed one value. The tutorial explains that a method is declared with an explicit first argument representing the object, and that the call supplies it implicitly. So a.deposit(50) behaves like Account.deposit(a, 50). By convention the first parameter is named self.
Forgetting it is a common beginner error:
class Oops:
def hello():
return "hi"
Oops().hello()
TypeError: Oops.hello() takes 0 positional arguments but 1 was given
Python passed the object in automatically, and the method had no parameter to receive it.
Class variables and instance variables
The tutorial separates two kinds of data. Instance variables, set through self, are unique to each object. Class variables, defined in the class body, are shared by all instances. A class variable fits something like a counter of how many objects exist:
class Counter:
created = 0
def __init__(self):
Counter.created += 1
x = Counter()
y = Counter()
print(Counter.created, x.created, y.created)
2 2 2
All three names show the same shared value.
The shared-list trap
The tutorial warns that shared data can surprise you with mutable objects such as lists and dictionaries, and that a list should not be a class variable when each object needs its own. Here is the mistake, then the fix:
class BadList:
items = []
def add(self, v):
self.items.append(v)
p = BadList()
q = BadList()
p.add("a")
q.add("b")
print(p.items, q.items)
['a', 'b'] ['a', 'b']
Both objects use the one list on the class. Create the list inside __init__ instead:
class GoodList:
def __init__(self):
self.items = []
def add(self, v):
self.items.append(v)
p = GoodList()
q = GoodList()
p.add("a")
q.add("b")
print(p.items, q.items)
['a'] ['b']
Now each object has its own list.
Inheritance
A new class can build on an existing one. You name the base class in parentheses, and the new class gets its methods; the tutorial adds that it can override any of them. Here a savings account adds an interest rate and one new method:
class Savings(Account):
def __init__(self, owner, balance=0, rate=0.02):
Account.__init__(self, owner, balance)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate)
s = Savings("Ana", 200)
s.add_interest()
print(s.summary())
Ana: 204.0
Account.__init__(self, owner, balance) runs the base class setup, so owner and balance still get stored. The balance is 200 plus 2 percent of 200, which is 4, for 204.0. The result shows a decimal point because multiplying by 0.02 produces a float.
The tutorial names two helper functions for checking relationships:
print(isinstance(s, Account), isinstance(a, Savings), issubclass(Savings, Account))
True False True
A savings account is an account, but the plain account a is not a savings account. The built-in function reference adds that a class counts as a subclass of itself.
When a class is worth it
If you only need a few named values, a dictionary may be enough. A class starts to pay off when the same data always travels with the same operations, as balance does with deposit and withdraw, or when you need several independent copies.
Frequently asked questions
What does the init method do in a Python class?
Python calls __init__ right after it creates a new instance, passing in the arguments you gave the class. In Account("Mia", 100), the method receives owner="Mia" and balance=100 and stores them as self.owner and self.balance.
Is self a keyword in Python?
No. It is only the conventional name for the first parameter. The Python tutorial notes that the name has no special meaning to Python, but other programmers and tools expect it, so keep using self.
Should the init method return the new object?
No. __new__ creates an instance, and __init__ customizes it afterward. Do not write return self in __init__: returning anything other than None raises TypeError. Store the starting values as attributes instead.
Does a child class automatically run the parent's initializer?
A child with no initializer of its own can inherit the parent's. If the child defines its own __init__, it must explicitly call the parent's initializer to perform that part of the setup. The Savings example uses Account.__init__(self, owner, balance); super().__init__(owner, balance) is another way to invoke the parent setup in this example.
What error appears if I forget self?
Calling the method on an instance passes the instance in automatically, so a method defined without self receives one argument more than it accepts and Python raises TypeError. How to read a Python error message shows how to find the failing line in the traceback.
What to check when adapting the example
These examples use Python 3 class and method behavior. Check where each value is assigned: self.balance belongs to the instance, while Counter.created belongs to the class. For lists, also check where the empty list is created. Two variables can refer to the same mutable object; a separate variable name does not itself make a copy. Creating a new list inside each initializer is what separates the GoodList objects.
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published