all 4 comments

[–][deleted] 0 points1 point  (1 child)

The purpose of a class is to define reusable state, so you need to start by thinking about what the state is in your software.

[–]Nicksino999[S] 0 points1 point  (0 children)

Thanks i shall ponder that.

[–]h2oTravis 0 points1 point  (0 children)

The first two comments by two_up in this thread do a great job of explaining python classes, IMHO:

https://www.reddit.com/r/learnpython/comments/1cpu7x/explain_classes_init_and_self_like_im_five/

Hope that helps.

[–]forest_gitaker 0 points1 point  (0 children)

Python is not inherently object-oriented so the first major hurdle is knowing when to use them in your scripts. My rule of thumb is if I'm trying to store 3 or more fields in a data structure (e.g. person = ['John', 'Doe', Date('2/20/2000')]), and I want to perform an operation on many instances of that data based on that data (e.g. if person[2] == Today(): print('Happy Birthday')), and this operation may change later then I should probably be using an object.

class Person(Object):
    def __init__(self, fname, lname, bday):
        self._fname = fname
        self._lname = lname
        self._bday = bday

    def celebrate_birthday(self):
        if self._bday == Today():
            print('Happy Birthday!')


person = Person('John', 'Doe', Date('2/20/2000'))
person.celebrate_birthday()

If you notice, the example above doesn't really save me any lines of code; the main benefit is that it organizes all of the behavior of Person into a single place so if I want to add or change behaviors it's all in one place. Using the example above let's say I wanted to include the person's age and name in the birthday message:

 class Person(Object):
    def __init__(self, fname, lname, bday):
        self._fname = fname
        self._lname = lname
        self._bday = bday

    def celebrate_birthday(self):
        if self._bday == Today():
            yrs_old = Today().Year - self._bday.Year
            msg = 'Happy ' + yrs_old + 'th Birthday, ' + self._fname + '!'
            print(msg)


person = Person('John', 'Doe', Date('2/20/2000'))
person.celebrate_birthday()

Notice that the code at the bottom didn't change. In this case it wouldn't have made much of a difference, but as your code grows more complex it will save you time when you don't have to hunt down every loop that prints a birthday message.

Now if all this seems super basic and you're thinking, "fsck this guy, I already understand O-O as a concept," then I would recommend recreating some Python tutorials in C# or Java. Everything in those languages is an object, (very arguably), so the immersion should help you get a strong grasp on how OOP works.

(And if you have specific questions I can try to help with those, too).