Introduction
Object initialization flow shows how a new object is created and set up with starting values in a program.
Jump into concepts and practice - no test required
class ClassName: def __init__(self, param1, param2): self.param1 = param1 self.param2 = param2
class Dog: def __init__(self, name): self.name = name my_dog = Dog("Buddy") print(my_dog.name)
class Car: def __init__(self, brand, year): self.brand = brand self.year = year car1 = Car("Toyota", 2020) print(car1.brand, car1.year)
class Person: def __init__(self, name, age=30): self.name = name self.age = age p = Person("Alice") print(p.name, p.age)
class Book: def __init__(self, title, author): self.title = title self.author = author print(f"Book '{self.title}' by {self.author} created.") my_book = Book("1984", "George Orwell") print(f"Title: {my_book.title}") print(f"Author: {my_book.author}")
__init__ method in a Python class?__init____init__ method runs automatically when a new object is created from a class.__init__ does__init__ initializes objects [OK]__init__ method that takes a parameter name in a Python class?__init__ method signatureself to refer to the new object.name argument, it must be added after self.class Car:
def __init__(self, brand):
self.brand = brand
my_car = Car('Toyota')
print(my_car.brand)my_car = Car('Toyota') calls __init__ with 'Toyota' as brand.brand attribute of my_car is set to 'Toyota', so printing my_car.brand outputs 'Toyota'.class Person:
def __init__(self, age):
age = age
p = Person(30)
print(p.age)age = age, which only reassigns the local variable, not the object's attribute.self.age = age.class Book:
def __init__(self, title, author='Unknown'):
self.title = title
self.author = author
b1 = Book('Python 101')
b2 = Book('Learn AI', 'Alice')b1.author and b2.author?author parameter has a default value 'Unknown', used if no argument is given.b1 is created with only title, so author defaults to 'Unknown'. b2 provides 'Alice' explicitly.