Sub topic 2
Initializing objects with __init__ and self
This chapter assumes you can write Python functions with default arguments, use lists and dictionaries, and run a script or the REPL. It also assumes you have seen the class statement. Here you will learn what happens when you call a class, why every method takes self, and which mistakes in __init__ cause most of the confusing errors.
What happens when you call a class
Calling a class looks like calling a function:
class Account:
def __init__(self, owner, balance=0):
if balance < 0:
raise ValueError("balance cannot be negative")
self.owner = owner
self.balance = balance
acct = Account("Ada", 50)
print(acct.owner, acct.balance) # Ada 50
print(vars(acct)) # {'owner': 'Ada', 'balance': 50}The call Account("Ada", 50) runs two steps:
- Python calls
Account.__new__to allocate a new, empty instance. You almost never write this method yourself, because the default one fromobjectis enough. - Python calls
Account.__init__(instance, "Ada", 50)to fill that instance with state. It then returns the instance to the caller.
__init__ is an initializer, not a constructor. The object already exists when __init__ starts. Its only job is to set up the object's state.
You can watch both steps by defining both methods:
class Traced:
def __new__(cls, *args, **kwargs):
print("__new__ called with", args)
return super().__new__(cls)
def __init__(self, value):
print("__init__ called with", value)
self.value = value
t = Traced(10)
# __new__ called with (10,)
# __init__ called with 10__new__ receives the class (cls) and the same arguments as the call. __init__ receives the new instance and those arguments. You need __new__ only for rare cases such as immutable types (subclasses of tuple or int) and singletons. For ordinary classes, write __init__ and leave __new__ alone.
What self is
self is the name, by convention, of the first parameter of an instance method. It refers to the instance the method was called on. Python does not treat the name specially, and you could call it this. Don't, because every Python reader and tool expects self.
The parameter is explicit because of how method calls work. The two calls below do the same thing:
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
c = Counter()
print(c.increment()) # 1
print(Counter.increment(c)) # 2
m = c.increment # a bound method
print(m.__self__ is c) # True
print(m.__func__ is Counter.increment) # TrueCounter.increment is a plain function stored on the class. When you write c.increment, Python finds that function and wraps it together with c into a bound method. Calling the bound method inserts c as the first argument. So c.increment() becomes Counter.increment(c).
This explains one of the most common error messages:
class NoSelf:
def greet():
return "hi"
try:
NoSelf().greet()
except TypeError as exc:
print(exc) # NoSelf.greet() takes 0 positional arguments but 1 was givenThe message says "1 was given" even though you passed nothing. The extra argument is the instance Python inserted. The fix is to add self to the signature.
Rules for __init__
It must return None
__init__ does not return the new object. The class call does that. If __init__ returns anything other than None, Python raises an error:
class Bad:
def __init__(self):
return 5
try:
Bad()
except TypeError as exc:
print(exc) # __init__() should return None, not 'int'An early bare return is allowed. It is useful when the rest of the setup is conditional.
It can raise to reject bad input
If __init__ raises an exception, the call fails and the caller never receives an instance. Account("Ada", -5) raises ValueError, and no half-built account exists afterward. Validating arguments here keeps invalid objects from existing at all.
Attributes come from assignment
Python has no attribute declarations. An attribute exists once you assign it, so self.owner = owner creates owner on that one instance. Assign every attribute the object will need inside __init__, even when the value is None for now. Then every instance has the same set of attributes, readers can see the object's shape in one place, and you avoid AttributeError from methods that run before a later setter.
class Download:
def __init__(self, url):
self.url = url
self.data = None # filled in later, but declared here
self.finished = False
def complete(self, data):
self.data = data
self.finished = TrueArguments work as in any function
__init__ accepts defaults, *args, **kwargs, and keyword-only parameters. Keyword-only parameters are a good choice when a constructor takes several values of the same type, because the call site documents itself:
class Server:
def __init__(self, host, *, port=8080, use_tls=False):
self.host = host
self.port = port
self.use_tls = use_tls
s = Server("example.org", port=443, use_tls=True)
print(s.host, s.port, s.use_tls) # example.org 443 TrueCalling Server("example.org", 443) raises TypeError, which prevents a swapped or ambiguous argument.
Common errors
Forgetting the self. prefix
Assigning to a bare name creates a local variable. It disappears when __init__ ends:
class Lost:
def __init__(self, value):
value = value # assigns the parameter to itself; nothing is stored
obj = Lost(3)
print(hasattr(obj, "value")) # FalseThe correct line is self.value = value. The same mistake inside other methods is just as common. If a later method raises AttributeError for an attribute you thought you set, check for a missing self..
Mutable default arguments
Default values are evaluated once, when the def statement runs, not on each call. A list or dictionary default is therefore one object shared by every call that relies on it:
class Team:
def __init__(self, name, members=[]): # bug: one shared list
self.name = name
self.members = members
a = Team("a")
b = Team("b")
a.members.append("Ann")
print(b.members) # ['Ann']Use None as the default and create the container inside the method:
class FixedTeam:
def __init__(self, name, members=None):
self.name = name
self.members = list(members) if members is not None else []
a = FixedTeam("a")
b = FixedTeam("b")
a.members.append("Ann")
print(b.members) # []The list(members) call also copies a list passed in by the caller. Without the copy, self.members and the caller's variable would refer to the same list, and changes on one side would show up on the other. Copy when your object should own its data. Don't copy when sharing is the intent.
Wrong number of arguments
TypeError: __init__() missing 1 required positional argument: 'age' means the call supplied fewer values than __init__ needs, not counting self. The message names the missing parameter, so read it before changing anything. The reverse error, "takes 2 positional arguments but 3 were given", counts self. A signature __init__(self, name) therefore reports "takes 2" when you pass two values.
Calling __init__ again
You can call obj.__init__(...) on an existing object, and it will reset the attributes it assigns. That is legal but rarely a good idea. If you need a reset operation, write a method called reset() and have __init__ call it.
Doing too much work
__init__ runs on every instantiation. Opening network connections, reading large files, or starting threads there makes the class slow to create and hard to test. Keep it to storing and validating values. Put heavy work in a separate method, or in an alternative constructor, a topic for the classmethod chapter.
When a subclass defines __init__
If a subclass defines its own __init__, Python does not run the parent's __init__ for you. The parent's attributes will not exist unless the subclass calls it explicitly. The inheritance chapters cover this with super().__init__(). For now, remember that __init__ is looked up like any other method, so the most specific class wins.
Choosing what to put in __init__
| Put in `__init__` | Leave out of `__init__` |
|---|---|
| Assignments of every instance attribute | Network, disk, or database access |
| Validation that rejects impossible values | Long computations |
| Copies of mutable arguments the object owns | Side effects that surprise the caller |
| Defaults such as `None`, `0`, or an empty list | Logic that belongs to a separate method |
Exercises
Exercise
This class is meant to give every playlist its own list of songs, but Playlist("a").songs is Playlist("b").songs returns True. Find the cause and write the fix.
class Playlist:
def _init_(self, title, songs=[]):
self.title = title
self.songs = songs
Show answer
The default [] is created once, when the def runs, so every instance that omits songs shares that one list. Use None as the default and create a new list inside the method:
class Playlist:
def _init_(self, title, songs=None):
self.title = title
self.songs = list(songs) if songs is not None else []
The list(songs) call also copies a list the caller passes in, so the playlist owns its data.
Exercise
Write a class Rectangle whose __init__ takes width and height, raises ValueError if either is not positive, and stores both. Then explain why Rectangle(0, 5) leaves you with no object, even though __new__ already ran.
Show answer
class Rectangle:
def _init(self, width, height):
if width <= 0 or height <= 0:
raise ValueError("width and height must be positive")
self.width = width
self.height = height
`new allocates the instance, but the class call returns it to the caller only after init finishes. When init_` raises, the exception propagates out of the class call, so the caller gets an exception instead of an instance. The half-built object is discarded.
Exercise
A method is defined as def total(items): inside a class and called as cart.total(). Python reports "takes 1 positional argument but 2 were given" when you call cart.total([1, 2]). Explain the arithmetic and say what the signature should be.
Show answer
The bound method inserts the instance as the first argument, so cart.total([1, 2]) calls total(cart, [1, 2]), which is two arguments for a function that accepts one. The signature should be def total(self, items):. In the no-argument call cart.total(), the instance would also be bound to items, which hides the mistake until the body uses it.