0

I am new in Python OOP and I try to understand one specific line of code.

This is a part of a code:

from random import randrange

class Pet():
    hunger_threshold = 10
    
    def __init__(self, name = "Kitty"):
        self.name = name
        self.hunger = randrange(self.hunger_threshold)

My question is, what is the different between

self.hunger = randrange(self.hunger_threshold) #1)

and

self.hunger = randrange(hunger_threshold) #2)

And why is it valid to to the 2) before doing

self.hunger_threshold = hunger_threshold

I hope someone can get me understanding.

Yokanishaa
  • 75
  • 5
  • #2 should give an error. – interjay Jul 03 '22 at 13:29
  • If you're asking what the purpose of `self` is, it's been answered [here](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-self-parameter-for-methods) –  Jul 03 '22 at 13:34
  • 1
    variable hunger_threshold declared for the class. it will be shared for all instances. to access it you can do self.hunger_threshold or Pet.hunger_thresold. you cant simply access it by hunger_threshold – Ritwick Jha Jul 03 '22 at 13:37

0 Answers0