I want to know why the following codes work?
#!/usr/bin/env python3
import sys
class Car():
def __init__(self):
pass
if __name__ == '__main__':
c = Car()
c.speed = 3
c.time = 5
print(c.speed, c.time)
I accidentally found that I don't have to init attributes in init. I learn from every tutor I have to put assignment in init like below.
#!/usr/bin/env python3
import sys
class Car():
def __init__(self):
self.speed = 3
self.time = 5
if __name__ == '__main__':
c = Car()
print(c.speed, c.time)
If there are some official documents can explain this would be better.
It's class attributes vs instance attributes vs dynamic attributes. When you do:
speed
andtime
are dynamic attributes (not sure if this is an official term). If the usage of the class is such that these attributes are set before calling any other methods ofCar
, then those methods can useself.speed
. Otherwise, you get an error:This happens because for
c
, speed and time are attributes on that instance ofCar
. Their existence or value doesn't propagate across other instances of Car. So when I created
and then try to lookupd.speed
, the attribute doesn't exist. As you've said in your own comment, "they spring into existence when they are first assigned to."Your tutors were very wrong or you misunderstood what they meant. In the example you gave, every Car gets the same initial
speed
andtime
. Typically, an__init__
would look like this:You can then initialise a
Car
with:c = Car(3, 5)
. Or put default values in init if it's optional.Edit: example adapted from the docs: