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
Gordon Reeder
2,521 PointsOO Python conventions.
So, when writing Object oriented Python, Should I strive to have all the code encapsulated in classes? Or can some procedural code be left to run outside all the classes and objects? What is the best practice?
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsIt's certain valid to have helper functions that do not exist within a class. I like to think of classes representing "things", "entities", something represented by a "noun". Classes, along with their attributes, are "database worthy" or something that you would want to persist. The functions (or methods) within the class operate on some aspect of the this entity, and can something be though of actions or "verbs".
Sometimes you have functions that operate on data that isn't part of a class attribute, so a class method wouldn't make sense.
A final bit of a twist is that all items in Python are objects: functions, strings, classes. So, in reality, everything you do is OO. :-)
Gordon Reeder
2,521 PointsGordon Reeder
2,521 PointsOk, thanks Chris. I should probably explain where I'm coming from. I have been taking Kenneth Love's Python courses. It is my first real dive into OO programming. In any case; At one point in the course he wrote a little dungeon game where a player has to find his way out of a dungeon while avoiding a monster. I added some improvements: monster chases player, door is locked and player needs to have a key, a weapon is laying around for the player to find, etc. Anyway, it was all written in procedural code. No class definitions. Then, when I got through the OO part of the course, I decided to rewrite the dungeon game using OO techniques. So I created several classes:
The thing is; I still have about 50 lines of code that exists outside any classes. It's fairly simple code that is the basic game loop. And so I'm wondering if this violates the spirit or best practices of OO programming.
Chris Freeman
Treehouse Moderator 68,468 PointsChris Freeman
Treehouse Moderator 68,468 PointsIt is definitely not bad form to have code outside of classes. It is very common to have a
def main():function that is called to start up and run the game loop.Gordon Reeder
2,521 PointsGordon Reeder
2,521 PointsIn case you're interested; you can see the code here:
https://github.com/greeder59/Dungon.git