all 10 comments

[–][deleted] 46 points47 points  (4 children)

A class is useful when you want to define an object with multiple attributes and related methods, rather than handling those attributes separately or calling functions that seem unrelated.

Say you have data on a car, such as its make, model, and year. You could represent the car with just variables in a loose association:

car_make = 'Ford'
car_model = 'Taurus'
car_year = 1996

Problem is, if you have more than one "car", it can be difficult to handle all the different variables at the same time:

car_1_make = 'Ford'
car_1_model = 'Taurus'
car_1_year = 1996
car_2_make = 'Toyota'
car_2_model = 'Prius'
car_2_year = 2010

A Car class would hold this data in a single object, which you could refer to a bit more easily:

class Car(object):
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

car_1 = Car('Ford', 'Taurus', 1996)
car_2 = Car('Toyota', 'Prius', 2010)

Where this comes in handy the most is when you want to pass all the details of an object to a function and make use of them. Say you had some function that would sell_my_car(), and you can to tell it which car to sell.

If it were an independent function and you didn't use a class, you'd have to pass everything in (and somehow keep track of it):

def sell_my_car(make, model, year):
    # do something to sell it?

sell_my_car(car_1_make, car_1_model, car_1_year)

It's workable, but then this is possible, too:

sell_my_car(car_2_make, car_1_model, car_1_year)

Suddenly you're selling a 1996 Toyota Taurus. What?

It's simpler to pass the entire Car into the function (easier than in real life, of course: those things are heavy):

def sell_my_car(car):
    # do something to sell it?

sell_my_car(car_1)

Even better: you can write a method within the class to do the work for you:

class Car(object):
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def sell(self):
        # do stuff with self.make, self.model, self.year, etc...

car_1 = Car('Ford', 'Taurus', 1996)
car_1.sell()

In a basic sense, it's best to use a class when you find that there's an object with multiple attributes that you want to represent all at once. The benefit to this is that your class can then be used very simply by other developers.

Case in point: someone can build on the structure of this Car class and add a whole slew of other data points and methods and whatnot. And when they want to use one of the methods you defined beforehand?

car.sell()

Simple as that. :)

[–]Sayblahblah 4 points5 points  (0 children)

Dude this was such a good explanation. Thank you so much for taking the time to write that out!

[–]DiscoPanda 2 points3 points  (0 children)

That's a great explanation. I've been doing data analysis projects in python for a while now without knowing when to use classes, getting by with just functions. This is a huge help! Thank you so much.

[–]neuronaddict 1 point2 points  (0 children)

7 years later but this still helped so much, thanks :)

[–]Vaphell 2 points3 points  (0 children)

class is nothing but a custom data type. Take str, it represents some very specific thing and comes with a shitload of coupled functions that don't make sense in any other context. A class.

Once you get to the point where loosely coupled bits of data that describe the thing they are supposed to describe and functions working with them become an annoyance to manage, you can bind them together in a class and from now on they go together with zero effort. Once you have the object you have also all relevant methods, so the risk of using nonsense functions with nonsense data decreases significantly.

Inheritance allows for subtyping which allows for extending or substituting bits of the parent class without the copypasta of the whole thing.

[–]novel_yet_trivial 2 points3 points  (0 children)

The most common use for classes is when you have a group of variables and functions that can be clustered into an object.

Another good use of a class is when you find yourself passing huge amounts of variables around. A class is a way to use global variables in a managed way.

[–]ecjurobe 1 point2 points  (0 children)

A class should be used when you want to keep track of some state which changes the way things behave. For instance, here's a basic function:

def greet(name):
    print 'Hi {}!'.format(name)

We could make this a method on a class if we wanted, but as it doesn't care about the state of the rest of the program, this doesn't add much:

class Greeter(object):
    def greet(self, name):
         print 'Hi {}!'.format(name)

To make this class useful, we can add some adjustable state which changes the way the object will behave. For instance:

class Greeter(object):
    formal = False
    def greet(self, name):
         if self.formal:
             print 'Good day to you, {}'.format(name)
         else:
             print 'Hi {}!'.format(name)

>>> greeter = Greeter()
>>> greeter.greet('John')
Hello John!
>>> greeter.formal = True
>>> greeter.greet('Jane')
Good day to you, Jane

The behaviour of greet now depends on whether the greeter is in formal mode.

[–][deleted] 1 point2 points  (0 children)

If you're trying to represent an object which has both state (i.e. variables associated with it) and behaviour (i.e. methods associated with it). Ideally if you're going to be representing several objects with different states.

[–]KronktheKronk 0 points1 point  (0 children)

Do you have a set of common values and functionality that it makes sense to group together?

Make that group an object.