Using self in python

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

Hello!

What you are doing there is you are creating a property of the class with self.name 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 instance.property. For example:

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

p1 = Person("John", 36)

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

p2 = Person("Sarah", 34)

print(p1.name) # "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