james
james

Reputation: 171

Unable to understand how objects work in Python

I am learning Python and noticed this program.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    self.printInfo = self.name + " is " + self.age + " years old!"

jack = Person("Jack", "30")
print(jack.name)
print(jack.age)
print(jack.printInfo)

jack.name = "Abel"
print(jack.name)
print(jack.printInfo)

Why does the last print statement print "Jack" instead of Abel?

Upvotes: 0

Views: 52

Answers (2)

Guy
Guy

Reputation: 50819

As mentioned before self.printInfo is initialized in __init__ so changing self.name will not change it. If you want a dynamic Person representation you can override __str__

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

    def __str__(self):
        return self.name + " is " + self.age + " years old!"


jack = Person("Jack", "30")
print(jack.name)
print(jack.age)
print(jack) # Jack is 30 years old!

jack.name = "Abel"
jack.age = "25"
print(jack.name)
print(jack) # Abel is 25 years old!

Upvotes: 2

TerryA
TerryA

Reputation: 59974

When you instantiate the object jack, it creates self.printInfo in the initialiser. It sets self.printInfo = self.name + " is " + self.age + " years old!", i.e, self.printInfo = Jack is 30 years old!.

This is a constant value. It does not change when self.name changes.

Upvotes: 1

Related Questions