Using __init__ in classes is fundamental for initializing(getting data in from outside) to the newly created objects.
While it's true that you can manually set attributes on an instance as in your second example.
Also try
Classes with an
Anyone reading your code can easily understand what attributes an instance of the class is expected to have and what initial state it will be in.
Consistency:
Using
Without __init__ you rely on manually setting attributes after object creation,
which can lead to errors or inconsistencies if some attributes are forgotten or mistyped
So can also add documentation and eg type hint to make even more clear what the class dos.
Then will see when create a object that it need a
While it's true that you can manually set attributes on an instance as in your second example.
Also try
len(a)
and see that it won't work as that what __len__
dos in my class.Classes with an
__init__
method are generally more readable and maintainable.Anyone reading your code can easily understand what attributes an instance of the class is expected to have and what initial state it will be in.
Consistency:
Using
__init__
ensures that every instance of the class is initialized consistently.Without __init__ you rely on manually setting attributes after object creation,
which can lead to errors or inconsistencies if some attributes are forgotten or mistyped
So can also add documentation and eg type hint to make even more clear what the class dos.
Then will see when create a object that it need a
list of int
and help(MtList)
will work.class MyList: """A custom list class that encapsulates a list and provides special methods to interact with its data. """ def __init__(self, data: list[int]): self.data = data def __contains__(self, item: int) -> bool: """Check if the item exists in the data.""" return item in self.data def __len__(self) -> int: """Return the number of items in the data.""" return len(self.data)To give one more example the more realistic as there often several values that you what to initialized class with.
class Car: """Represents a car with specific attributes and capabilities.""" def __init__(self, color: str, mileage: float, fuel_efficiency: float): self.color = color self.mileage = mileage self.fuel_efficiency = fuel_efficiency def calculate_gas_usage(self, distance: float) -> float: """Calculate the amount of gas used over a given distance.""" return distance / self.fuel_efficiency def __repr__(self): return f"Car(color={self.color!r}, mileage={self.mileage}, fuel_efficiency={self.fuel_efficiency})" def __str__(self): return f"A {self.color} car with {self.mileage} miles, fuel efficiency {self.fuel_efficiency} mpg."Use this class.
>>> my_car = Car('red', 10, 14.5) >>> # This work because of __repr__ >>> my_car Car(color='red', mileage=10, fuel_efficiency=14.5) >>> # This work because of __str__ >>> print(my_car) A red car with 10 miles, fuel efficiency 14.5 mpg. >>> my_car.calculate_gas_usage(100) 6.896551724137931
>>> help(Car) Help on class Car in module __main__: class Car(builtins.object) | Car(color: str, mileage: float, fuel_efficiency: float) | | Represents a car with specific attributes and capabilities. | | Methods defined here: | | __init__(self, color: str, mileage: float, fuel_efficiency: float) | Initialize self. See help(type(self)) for accurate signature. | | __repr__(self) | Return repr(self). | | __str__(self) | Return str(self). | | calculate_gas_usage(self, distance: float) -> float | Calculate the amount of gas used over a given distance.