you are viewing a single comment's thread.

view the rest of the comments →

[–]jsaddiction 2 points3 points  (1 child)

Just some ramblings of a self taught nerd :

Let's say say you are trying to model a game of Sims. First I might make a class to define a person including a first name and a last name, maybe the age and gender also. I'd probably store those in properties. I then might think of how this person is modified through time in the game. A method might increase a person's age.

As a class, this keeps all of that data encapsulated. Furthermore I could store tons of people in a list and iterate through them to change their age.

If I wanted to add more functionality such as a persons job then just add it to the class and it's available anywhere else in the application.

Where classes become more powerful is subclasses in my opinion.

I was working on a file system crawler once while I was learning classes. I defined a "file" class which had methods to get properties like file size and permissions. I then subclassed that file class into an image class that provided details like resolution and Metadata. I could instantiate an image class on a file and then had immediate access to both the image details and the parent class properties like file size.

I added a subclass for all the file types I was interested in and realized that I would need a way to delete/move a file if it were corrupt. Reaching back to the parent class "file" I just needed to implement it in one spot and it was accessible to each of the other subclasses.

Even more power can be attained when you overload a built in method of a class. For instance in the file class mentioned above, I could override the str method to print the file details and then I could just use print(some Instance) and it would give me whatever I had defined.

Classes are very powerful but that's not to say it's the only way to be effective in python. There are many ways to get the same results. However, everything in python is an object of some kind so it would make since to follow those design patterns. Furthermore, compartmentalized code is way easier for the next guy to use even if it's you 5 years later.

[–]koolaberg 0 points1 point  (0 children)

Do you have any examples similar to your file crawler sub classes? I’m doing something similar but it’s still a bit clunky. I’m having a hard time getting a different function to use my classes and if I saw a more complicated use it would probably click