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) Hack-n-Slash Last Steps For Character

Jeff Hartl
Jeff Hartl
Python Web Development Techdegree Student 8,420 Points

Why not put "def __init__" before other methods in character.py?

In Kenneth's code for the Character class (character.py), he put the def __init__ method below the methods attack() and get_weapon(self). This looks funny to me -- funny/strange, not funny/ha-ha (highly technical phrasing, I know).

If I understand correctly, when a instance of a class is created, the order in which the methods were written in the underlying .py file isn't always crucial. However, wouldn't this particular code look cleaner and be easier to read if def __init__(self, **kwargs) were the first method (after any defaults are declared, of course) that we come across in the Character class definition?

In general, when writing a class, shouldn't the__init__ method come before any other methods within the class? Not for the sake of functionality, but for readability?

3 Answers

Steven Parker
Steven Parker
229,644 Points

It makes sense to me also, but I checked the PEP8 and didn't find it in there. It did say that module-level "dunder" names should come before others, and before imports. But no mention of method-level names.

So I guess it's not generally considered that important. Seems like it would be a good practice though.

Shailesh Gupta
Shailesh Gupta
12,885 Points

It doesn't matter where we put our methods in the class as long as it doesn't cause errors. As python is interpreted language (code is executed line by line). So, the methods which call another method must come after. For example:

def A(): #some code def B(): A() #some code

Thus, if B() is calling A(), so it must come after A(). So is the case with all the method calling. It doesn't matter where we put int() methods (magical methods) as long as they obey calling procedures.

I hope this solves the issue.

@ Jeff Hartl. I too had this question and concern. I think it is good practice to always define init(self): as the first method after creating a Class. I usually think of it as the 'Boot up sequence' if you will. While apparently not necessary to be first, I think it does have a much cleaner and neater look or "Readability", like you said. Great question Jeff.