The messaging in this course seems to be that OOP revolves around organization of code vs creating classes for the purpose of repeatable variance.
For example: Day 23 is a frogger game. The instructor creates a 'CarManager' class that generates the same car over and over. There doesn't seem to be any reason, other than organization of code, why the CarManager functions couldn't have been placed in the main.py file.
Question:
- I'm trying to distinguish and understand why a class would be created when the attributes and functions could very well be placed in the main.py with no difference in the amount of code written. Should a class be created simply for organizing and de-cluttering your main.py?
In the frogger game example, I took a different approach to what the instructor did (code below). I created a Car class with inputs for size and speed. Then in my main.py code, I generated 4 different vehicles using Car class (motorcycle, car, truck, semi) with varying size and speed. Is this not a more appropriate use of OOP within Python?
Car class:
from turtle import Turtle
import random
CAR_COLORS = ["blue", "red", "black", "green", "pink", "orange"]
class Car:
def __init__(self, size1, speed1):
self.car_pieces = []
self.car_list = []
self.create_car(size1)
self.speed = speed1
def create_car(self, car_size):
color2 = random.choice(CAR_COLORS)
xcor = random.randrange(310, 350, 20)
ycor = random.randrange(-235, 226, 40)
for i in range(car_size):
car_piece = Turtle()
car_piece.color(color2)
car_piece.shape("square")
car_piece.penup()
car_piece.setposition(xcor, ycor)
self.car_pieces.append(car_piece)
xcor += 20
def car_move(self):
for i in range(len(self.car_pieces)):
self.car_pieces[i].backward(self.speed)
main.py
#Car generation
car_list = []
motorcycle_speed = 12
car_speed = 5
truck_speed = 3
semi_speed = 1
def car_generator():
car_options = ["motorcycle", "car", "truck", "semi"]
car_choice = random.choice(car_options)
random_chance = random.randint(1,6)
if random_chance == 1:
if car_choice == "motorcycle":
motorcycle_object = Car(1, motorcycle_speed)
car_list.append(motorcycle_object)
elif car_choice == "car":
car_object = Car(2, car_speed)
car_list.append(car_object)
elif car_choice == "truck":
truck_object = Car(3, truck_speed)
car_list.append(truck_object)
elif car_choice == "semi":
semi_object = Car(4, semi_speed)
car_list.append(semi_object)
else:
pass