Using self in python

In the code below why do we have to define, self.age, and self.is_asleep?


What you are doing there is you are creating a property of the class with and then setting it to the value that was provided (input_name). This property can have a different value for every instance of the class and can be accessed with For example:

class Person:
  def __init__(self, name, age): = name
    self.age = age

p1 = Person("John", 36)

print( # "John"
print(p1.age)  # 36

p2 = Person("Sarah", 34)

print( # "Sarah"
print(p1.age)  # 34

So these properties are used to store and track information that is specific (and will vary) for different class instances. Another example would be if we had a Dog class, we could have age and breed as properties, as each Dog we create would have a different age and breed.

1 Like