Following an online tutorial, I typed up the following code:
class Car:
# define and initialize some attributes of Car object
def __init__(self):
self.speed = 0
self.odometer = 0
self.time = 0
# 'get' function for current speed
def say_state(self):
print("I'm going {} kph!".format(self.speed))
# 'set' function for current speed
def accelerate(self):
self.speed += 5
# 'set' function for current speed
def brake(self):
self.speed -= 5
# 'set' function for trip time and distance
def step(self):
self.odometer += self.speed
self.time += 1
# 'get' function for average speed
def average_speed(self):
return self.odometer / self.time
if __name__ == "__main__":
my_car = Car()
print("I'm a car")
while True:
action = input("What should I do? [A]ccelerate, [B]rake, "
"show [O]dometer, or show average [S]peed").upper()
if action not in "ABOS" or len(action) != 1:
print("I don't know how to do that.")
continue
if action == "A":
my_car.accelerate()
elif action == "B":
my_car.brake()
elif action == "O":
print("My car has driven {} kilometers".format(my_car.odometer))
elif action == "S":
print("My car's average speed was {} kph".format(my_car.average_speed()))
my_car.step()
my_car.say_state()
Then, I broke from the tutorial because it didn't tell me what the if __name__ == "main"
business was about. Reading elsewhere, I kind of understood that this statement prevents the code following that if statement from executing if the module isn't being run as the main class, but rather is imported. So to test this out I typed up another small module "import_practice.py:
import Car
corolla = Car()
corolla.say_state()
This code would not run, with the error "Car is not callable", so I figured my import was wrong. I replaced import Car
with from Car import Car
and it worked, but according to the following answer, it shouldn't make a difference, right? In fact, if that answer is correct, it isn't the behavior I'm looking to get out of my import at all.