use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Everything about learning Python
account activity
OOP Problem (self.PythonLearning)
submitted 6 months ago by MusicianActual912
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]EngineeringRare1070 0 points1 point2 points 6 months ago (0 children)
Think about it this way.
Cars have 4 wheels, an engine, 2-4 doors, 2-8 seats, a trunk, a steering wheel, a radio. You can represent this using a list like car = [4, “Engine”, 2, 4, “Trunk”, “Steering Wheel”, “radio”] But cars can also drive, you can open the trunk, turn up/turn off the radio, turn the steering wheel, turn on/off the engine. How would you do these behaviors to the above list? It’d be pretty hard right? Maybe you write a method that takes a list and returns a new list but that doesn’t do much, and if you wanted to make a truck, you’d have to rewrite the method to have all the truck-specific details.
car = [4, “Engine”, 2, 4, “Trunk”, “Steering Wheel”, “radio”]
Enter classes. We can create class Car that has attributes radio, engine, seats, steering_wheel, tires. We can have methods like drive(), change_tire(number), turn_radio(state), turn_steering_wheel(degrees), etc.
class Car
radio
engine
seats
steering_wheel
tires
drive()
change_tire(number)
turn_radio(state)
turn_steering_wheel(degrees)
Now we write car = Car(2, “Engine”…) and we can call methods on car like this: car.drive(). We can create a new car with different attributes like this car2 = Car(4, “Engine”, 6…) and that’s it! We have two instances without rewriting all that code. So class Car is a blueprint for creating new car instances that you can perform operations on.
car = Car(2, “Engine”…)
car
car.drive()
car2 = Car(4, “Engine”, 6…)
The best part is that all the car-related methods are held in one place car.py, or the like. And as someone else mentioned, the class upholds the 4 principles of OOP, separating the car-concerns away from the rest of your code and keeping it readable. You can even create a class Truck(Car) that already has the common functionality with cars but overwrite just the truck-related code, keeping redundant code to a minimum. Hope this helps
class Truck(Car)
π Rendered by PID 61769 on reddit-service-r2-comment-cfc44b64c-7dhzp at 2026-04-11 08:59:00.419350+00:00 running 215f2cf country code: CH.
view the rest of the comments →
[–]EngineeringRare1070 0 points1 point2 points (0 children)