Lesson explanation
__init__After this lesson, you will be able to:
__init__ and initialize instance attributes as an object is created.self.In the previous lesson, you created a class and attached attributes after constructing each object. That works, but it is easy to forget an attribute. Python's __init__ initializes an instance automatically when you call its class:
class Task:
def __init__(self, name, owner):
self.name = name
self.owner = ownerTask("build", "Maya") constructs an object and calls __init__ with the supplied arguments. Python supplies self automatically; you do not pass it yourself. Unlike a Java/C# constructor, __init__ is an initialization method, and it normally does not return a value.
Constructor parameters are temporary inputs. self.name and self.owner are instance attributes that remain available through the object. Every call constructs a separate instance with its own stored state.
Defaults from Unit 1 work in __init__ as well: def __init__(self, name, retries=0): lets callers omit a retry count. Put required parameters before optional ones.
class Endpoint:
def __init__(self, name, region):
self.name = name
self.region = region
endpoint = Endpoint("billing", "eu")
print(f"{endpoint.name}@{endpoint.region}")Output:
billing@euThe constructor inputs become persistent instance attributes.
class Deployment:
def __init__(self, tag, ready):
self.tag = tag
self.ready = ready
first = Deployment("v1.4", True)
second = Deployment("v1.5", False)
print(first.ready)
print(second.ready)Output:
True
FalseThe second object does not overwrite the first object's state.
class Queue:
def __init__(self, name, pending=0):
self.name = name
self.pending = pending
normal = Queue("email")
busy = Queue("reports", 4)
print(f"{normal.name}: {normal.pending}")
print(f"{busy.name}: {busy.pending}")Output:
email: 0
reports: 4The default applies only when the caller omits the argument.
class Wallet:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
wallet = Wallet("Ari", 20)
wallet.deposit(7)
print(f"Balance: {wallet.balance}")Output:
Balance: 27Methods change the initialized state using self, not a temporary local variable.
| Goal | Syntax |
|---|---|
| Initialize an instance | def __init__(self, name): |
| Keep a constructor input | self.name = name |
| Create an initialized object | obj = ClassName(value) |
| Supply an optional initial value | def __init__(self, name, count=0): |
| Update the object's state | self.count += amount |
name = name instead of self.name = name does not save an attribute on the instance.self raises AttributeError.__init__ raises a TypeError; use other methods to return results.