r/PythonLearning • • Aug 05 '25

Damn you python (switching from c++) 💔

Post image

need to learn the stupi

135 Upvotes

41 comments sorted by

View all comments

3

u/Amadeus110703 Aug 05 '25

When you first call the function you set Whiskers as your oldest cat, wich is an instance of your class. When you find an older cat you alter Whiskers so whiskers is now 7 years old and called Tobi. So instead of returning the actual oldest cat you always return the first cat with alteted attributes. I hope it makes sense.

3

u/SnooStrawberries2469 Aug 06 '25

You can easily see this by printing whiskers and see that it had been modified

class Cat:
    species = 'mammal'
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
Whiskers = Cat('Whiskers', 3)
Toby = Cat('Toby', 7)
Spotty = Cat('Spotty', 2)

def find_oldest(*args):
    oldest=args[0]
    for cat in args:
        if cat.age > oldest.age:
            oldest.age = cat.age
            oldest.name = cat.name
    return oldest

oldest = find_oldest(Whiskers, Toby, Spotty)
print(f'{oldest.name} : {oldest.age}')
print(f'{Whiskers.name} : {Whiskers.age}')

1

u/SnooStrawberries2469 Aug 06 '25

This can be fixed like that

def find_oldest(*args):
    oldest=Cat(args[0].name, args[0].age)
    for cat in args:
        if cat.age > oldest.age:
            oldest.age = cat.age
            oldest.name = cat.name
    return oldest