-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

3
  • 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 5, 2015 at 17:01
  • Possible duplicate of When is "self" required?. Additional reading: What is the purpose of self in Python?, Python init and self what do they do?.
    – Celeo
    Nov 5, 2015 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 5, 2015 at 17:47

2 Answers 2

0

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.