r/pythontips • • Sep 16 '21

Python3_Specific Just started OOP learning in Python, any help?

I'm quiet new to python, also it's my first language and I was playing around with classes and such and came up with a program that prints out some car detailsMy question is how to use the __add__ method to sum up more than 2 elements? Is it possible?

here is my code: https://imgur.com/a/HcSqArM

if I print(car1 + car2) it will print all details from both instancesbut how can I print all details for ALL four cars? how to use print(car1 + car2 + car3 + car4) to make it work ?

yes, I know I can just print(car1 + car2) and under it print(car3 + car4)but that would defeat the purpose of what I'm trying to understand :D

also print(str(car1 + car2) + '\n' + str(car3 + car4)) works too but not what I want

26 Upvotes

8 comments sorted by

6

u/mikeiavelli Sep 16 '21 edited Sep 16 '21

Interesting... a shortcut would be to use parentheses I guess, but make sure the left argument is always a Car object:

print(car1 + (car2 + (car3 + car4))) # This works

But don't do this:

print(((car1 + car2) + car3) + car4) # This DOES NOT work

because then it would try to use the String's __add__ method.

You can implement _radd_ to use it in that order though.

(Usual disclaimer: I did not try the code above)

Now the interesting part that I'd have to check is the "associativity" of the '+' operator here....

I'll come back later today if I have an answer.

---

EDIT: I thought about it after pushing that 'post' button and I'm not even sure the first part would work.... let me check your code a bit...

EDIT2: The way you implemented it, I think it works.

EDIT3: Now that I think about it, the second print statement would have the effect you want, but by accident: the '+' in that case uses the String's __add__ method, not the Car's __add__ method.

1

u/Vesedon Sep 16 '21

I did more research and I found out it's not so humane to do stuff like this anyway in this way since it does not really make sense to add two cars together that result in a string so I ended up using a custom function outside the classes

1

u/PhilAndMaude Sep 17 '21

I agree. In a real-life app, keeping the cars in a list will be 10 times as useful as keeping them in a string. You'll be able to sort them, delete entries, insert entries, replace entries, find entries.

# python3.8

class Car:
    def __init__(self, brand):
        self.brand = brand

    def __str__(self):
        return f'TYPE: NORMAL CAR\nBRAND: {self.brand}\n'

class SportCar(Car):
    def __init__(self, brand, engine):
        super().__init__(brand)
        self.brand = brand
        self.engine = engine

    def __str__(self):
        return f'TYPE: SPORT CAR\nBRAND: {self.engine}\n'

def print_things(thing_list: list):
    separator = '- ' * 15 + '\n'
    print(separator.join(str(thing) for thing in thing_list))

def run():
    car1 = Car('Honda')
    car2 = SportCar('Jaguar', 'clockwork')
    cars = [car1, car2]
    print_things(cars)

if __name__=='__main__':
    run()

2

u/ray10k Sep 16 '21

In your 'add' function, you return a string. Instead of doing that, eiter return a 'car' object so that adding multiple together will keep using the addition from the car class, or return some sort of intermediate class that tracks the cars that get added to it until the string representation is requested.

2

u/Vesedon Sep 16 '21

ended up using a function xd

def car_showcase():

show = (car1, car2, car3, car4)

line = '- ' * 15

for x in show:

print(x)

print(line)

car_showcase()

2

u/AJohnnyTruant Sep 16 '21 edited Sep 16 '21
  1. use keyword args with defaults in your init (better yet use another props class or dict but that’s a whole other thing). Too many positional arguments gets extremely difficult to manage later

  2. if you want proper SOLID design, your car should not know anything about printing details. A CarFormatter class (or function) should have a method that accepts any number of cars and returns the string. Then you can print that. Let’s say you wanted to use this with a command line then later on a web app. Your Car class shouldn’t have to change because you’re using it else where and it needs a new format

str and repr are really only there for debugging and logging. They’re not really there as presenters. You could have a Car().toDetailsSlug() or something but that’s still pretty brittle if you’re trying to present info to a user right off the Car instance.

Good grasp with the inheritance though. Great start

1

u/Vesedon Sep 16 '21

Thank you! Any example for the car formatter part ?

0

u/dummydummy123456 Sep 16 '21

i started learning oops from 22-08-2021 and still learning basics am slow learner its very hard for me to understand may be we both study to-gather for learning oops alone then we will think about learning others things to gather later what do you think? am doing 100 days python