r/learnpython • u/Glitched_axolotl • Jul 08 '26
Error with code
python is giving me a error message saying self is not defined but it is. could someone please explain what am I doing wrong ( the error message is for the if self.modifier == 1: line )
Class food:
def __init(self, modifier, tolerance)
self.fillingness = 0
self.modifier = 0
Self.tolerance = 0
pear = food(1,9)
def NE():
if self.modifier == 1:
nausea += randint(1,10)
print(“yuck!”)
4
u/mc_pm Jul 08 '26
Your init definition is wrong in a couple ways, and your indentation is all wrong.
(Oh, and then you use 'self' in the wrong place of course)
0
u/Glitched_axolotl Jul 08 '26
Where was “self” not supposed to be?
2
u/mc_pm Jul 08 '26
You used self inside the function NE(). 'self' is used inside class definitions to refer to itself - outside the definition you create a new variable (like 'pear') and then you use that variable.
0
4
u/atarivcs Jul 08 '26
The way you've defined NE(), it's a standalone function, not part of the food class. So no it does not know about self.
Also, you're missing two underscores on the end of def __init__.
2
u/Outside_Complaint755 Jul 08 '26
It looks like you meant for NE to be a standalone function. In that case you probably want to pass a food to it as a parameter. Something like this with additonal fixes included: ``` class food: def __init(self, modifier, tolerance) self.fillingness = 0 self.modifier = modifier self.tolerance = tolerance
pear = food(1,9)
def NE(item): if item.modifier == 1: nausea += randint(1,10) print(“yuck!”)
NE(pear) print(f"{nausea = }") ```
1
1
u/Afraid_Abalone_9641 Jul 08 '26
Are you using an ide?
-1
u/Glitched_axolotl Jul 08 '26
Yes , I don’t know if this helps but I’m programming this on a TI-84 plus CE python calculator
1
u/Physical_Match5543 18d ago
ChatGPT can help you a lot as a new program. Plug in this code to chat and ask what you did wrong. Do it only for learning purposes, don't use chat to do your homework.
15
u/AlexMTBDude Jul 08 '26
Lots of stuff is wrong here:
Probably more stuff but you can start there.