Say I create a class by the name of Car
. Would I be able to add instance attributes without having them already listed as a parameter in my __init__
method (constructor), and if so, why would we need to do something like this? So pretty much it would look something like this:
class Car():
def __init__():
self.something = something
Of course normally I would have more stuff but for this example I kept it minimal.
CodePudding user response:
Yes, you can create instance attributes in __init__
whose values are not parameters.
This can be the case, for example, if an attribute has a fixed initial value, or a value that is derived from other parameters or other context.
CodePudding user response:
You can, but the point of the class Car()
is to manage everything inside of it.
You do not want to create a Car
, and add the wheels outside of the class, becasue tomorrow you will forget, will try to ebug the code, and you will not know why 3 different types of wheels were added by code which you have no clue were it is.
you will find the some car
instances have car.wheels
, car.tires
, 8 wheels, will not know if car.tire
is a spare tire, or a working tire. It will be a mess.