Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Inheritance __str__

Help understanding a specific argument given to the format function

The str method (~1:40) returns a string using the .format function.

def __init__(self, **kwargs):
    self.hit_points = random.randint(self.min_hit_points, self.max_hit_points)
    self.experience = random.randint(self.min_experience, self.max_experience)
    self.color =  random.choice(COLORS)

for key, value in kwargs.items():
    setattr(self, key, value)

def __str__(self):
    return('{} {}, HP: {}, XP: {}'.format(self.color.title(),      #here

How is the str method able to access the color variable, when the self.color variable is defined in the init? I believe the answer I am looking for is an explanation on self with pointers.

1 Answer

Tom Sager
Tom Sager
18,987 Points

str is an instance method, which can only be called after init has been called. Init creates an instance. References to self within an object definition point to whatever instance was used to call that method.

So init creates an instance with a particular color, and str returns variables from that instance (such as color).

from monster import Dragon  # creates the Dragon class from the monster class
draco = Dragon()   # calls init, which creates a new instance named draco (with a color)
print(draco)       # calls str; draco is the instance, so 'self' points to draco