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!

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) Objects Class Methods

Iskander Ismagilov
Iskander Ismagilov
13,298 Points

Monster.battlecry() and Monster().battlecry()

class Monster:
  sound = 'roar'

  def battlecry(self):
    return self.sound.upper()

I have 2 questions:

  1. When importing Monster in shell, if: 1) Monster.battlecry() it gives TypeError: battlecry() missing 1 required positional argument: 'self' 2)Monster().battlecry() if returns 'ROAR' How parentheses after Monster affect on the result?

  2. jabber = Monster() So Monster.battlecry(jabber) == jabber.battlecry() I want to understand how jabber in jabber.battlecry() from argument of a method becomes a caller of it and it doesn't bring the TypeError of missing positional argument.

1 Answer

Keli'i Martin
Keli'i Martin
8,227 Points

So basically Monster is the class. In order to properly call the function battlecry(), you need an instance of the Monster class. This is accomplished by calling Monster(). In this case, the instance itself doesn't have a name.

Calling jabber = Monster(), you are creating another instance of the Monster class. This time, the instance does have a name, jabber. Since jabber is an actual instance of the class, you can call jabber.battlecry() without getting an errort.

Hope that clears it up a little.