-1

I'm learning about Classes in Python and I was given a very basic example:

class Person:
    def say_hi(self):
        print('Hello, how are you?')

p = Person()
p.say_hi()

The author states that we could have just as easily written: Person().say_hi()

So, why don't we do that instead of instantiating the Person class on the p variable?


On reflection, I would like to know why we need classes. I can do the say_hi() function without need for a class at all. I realise this is a very simple class but I'd like to know what classes can be used for / when is an appropriate time to use a class?

Charlotteis
  • 337
  • 1
  • 4
  • 10
  • 6
    The example you've been given is simplified to illustrate how classes work. You'd rarely actually use them if you aren't attaching any state (self.foo = bar). – Jeremy Jan 04 '15 at 22:41
  • 3
    Short answer: *to hold state.* Long answer: for the same reasons that all other object-oriented languages use classes. – Robert Harvey Jan 04 '15 at 22:42
  • 1
    The author is lying. – MightyPork Jan 04 '15 at 22:42
  • @Ben - I do indeed, thanks! – Charlotteis Jan 04 '15 at 22:43
  • It could also be `Person.say_hi(p)`, to supply the instance argument named `self`. But in this case, as there's no state, it should just be a function. – jonrsharpe Jan 04 '15 at 22:44
  • @RobertHarvey and why do all other object-oriented languages use classes? I think that may have been something I should have added into my question but I also fear that it is quite a broad question. – Charlotteis Jan 04 '15 at 22:47
  • Perhaps you should read on and learn more, before asking questions like this that are certain to be answered in pages to come. – Daniel Roseman Jan 04 '15 at 22:48
  • possible duplicate of [What are Class methods in Python for?](http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for) – buydadip Jan 04 '15 at 22:50
  • @Bolboa that isn't what I was looking for, but I think that's my fault as my question is very broad. – Charlotteis Jan 04 '15 at 22:57
  • [Started to write a response, but question got closed before posting.] One needs classes not only to store states (as others have pointed out), but also to make use of nice language features such as operator overloading, polymorphism/duck typing, code reuse through inheritance and many others. In short, you don't need classes as long as you use Python as a "glue language" to connect bits and pieces other people have written. As soon as you desire to implement pieces of your own, you will want to use classes because they will make your module as pleasant to use as the modules you are using now. – user4815162342 Jan 04 '15 at 23:03

1 Answers1

5

This question truly is too broad to get a complete answer, so let me give you one that fits the scope of your example, rather than the scope of your question.

As a few commenters have noticed, you use classes to give your functions a stateful environment to run in. Imagine I wanted to create a counter, for instance. I could use a global variable and a function, like:

counter = 0
def increment_counter():
    global counter
    counter += 1
def decrement_counter():
    global counter
    counter -= 1

but this pollutes our namespace with two extra function signatures and a variable. Plus the global keyword is a code smell that should be avoided when possible. Not to mention you can only have one such counter in your whole code base! If you needed another, you'd have to retype all that code and violate DRY (Don't Repeat Yourself).

Instead we create a class:

class Counter(object):
    def __init__(self):
        self.count = 0
        # initialize count at zero
    def increment(self, by=1):
        self.count += by
    def decrement(self, by=1):
        self.count -= by

Now you can instantiate that as many times as you'd like, and each one keeps track of its own separate count, e.g.:

counter_a = Counter()
counter_b = Counter()

for _ in range(3):
    counter_a.increment()
for _ in range(1000000):
    counter_b.increment()

assert counter_a.count == 3
assert counter_b.count == 1000000
Adam Smith
  • 52,157
  • 12
  • 73
  • 112