Class

class Dog():
  dog_time_dilation = 7

  def time_explanation(self):
    print("Dogs experience {} years for every 1 human year.".format(self.dog_time_dilation))

pipi_pitbull = Dog()
pipi_pitbull.time_explanation()

in method “time_explanation” why we need to put “self” infront of “dog_time_dilation”

self is used to determine which instance the method is called on:

class Test:
    def __init__(self, abc):
        self.abc = abc
    
    def print_abc(self):
        print(self.abc)

test = Test('hello abc')
test.print_abc()
Test.print_abc(test)

as you can see, when calling the method on instance, python is handling self. However, you can also call the method on the class, and then pass the instance as argument for self parameter.

Now, class variable are shared by all instances, so you can do self.dog_time_dilation or Dog.dog_time_dilation given class variables are the same for all instances

1 Like