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

getting the 'title' out of a subclass

So, I'm working on the dungeon game (with classes) and I'm trying to just get the name of the monster to print, i.e. no other info as in

'the troll lumbers towards you'

not

'the purple troll HP 5 XP 4 lumbers towards you'

and for the life of me I can't figure out how to do that.

It is a subclass of class Monster:

I figure I can just give the Troll class a name variable and call self.monster.name in the script but I'm trying to figure out how to do this the other way.

Any help would be appreciated.

thanks

ar

4 Answers

Jeremy Fisk
Jeremy Fisk
7,768 Points

Assuming you have the following def__str__(self)

def __str__(self):
    return'{} {}, HP: {}, XP {}'.format(self.color.title(),
                                        self.__class__.__name__,
                                        self.hit_points,
                                        self.experience)

then you can use the following code to get the result you are looking for:

print(" the {} lumbers towards you".format(troll.__class__.__name__))

That's very 'troll' specific. What if the monster that is attacking is, say, a dinosaur. Is there a more generic way to go about it?

Jeremy Fisk
Jeremy Fisk
7,768 Points

I would suggest that in your def__str__(self) remove all of the .format() arguments except self.__class__.__name__ and that would enable you to print a more general monster instance that you had instantiated in the manner you are envisioning.

Yeah, that's probably what I'll end up doing. I'm new to classes so I'm just trying a bunch of different ideas to see what is allowed and what is not. It's strange to me that I can't seem to pull the name of a subclass. Thanks for your help.