-1

I'm new to python and I've been trying to understand classes.

As far as I know, when you create a class, you must insert self before a variable, so that self is replaced by the instances, when they're created (these become instance attributes). Besides instance attributes, there are also class attributes, which are defined at the top of the class, before any methods.

However, I came across this code:

class Hero:
    def __init__(self, name):
        self.name = name
        self.health = 100

    def eat(self, food):
        if food == 'apple':
            health += 20
        elif food == "chocolate":
            health -= 10

Why doesn't food have self before it? It is not an instance attribute but it doesn't seem to me that it is a class attr either.. I'm using python 2.X

Acla
  • 141
  • 3
  • 12
  • Because `food` is a *parameter* of the method, not an *attribute* of the class/instance; it's passed in, e.g. `Hero('Hercules').eat('apple')`. That method doesn't refer to `self` at all, so could be a `@staticmethod`. – jonrsharpe Nov 05 '15 at 17:01
  • Possible duplicate of [When is "self" required?](http://stackoverflow.com/questions/280324/when-is-self-required). Additional reading: [What is the purpose of self in Python?](http://stackoverflow.com/q/2709821/2676531), [Python __init__ and self what do they do?](http://stackoverflow.com/q/625083/2676531). – Celeo Nov 05 '15 at 17:02
  • I was so focused on learning about class and instance attributes, that I completely forgot about simple function parameters. Thank you! – Acla Nov 05 '15 at 17:47

2 Answers2

0

food is not referring to the attribute of the class object (which would be self.food), but rather the parameter given to eat.

anOKsquirrel
  • 140
  • 1
  • 4
0
class Hero:
    def __init__(self, name):
        self.name = name
        self.health = 100

    def eat(self, food):
        if food == 'apple':
            self.health += 20 # <-------- use self. always if you want to use an attribute of the instance inside a method
        elif food == "chocolate":
            self.health -= 10
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95