Python Classes in 2 minutes!
It took me two rereadings of the Classes chapter to understand the difference between writing code in the interactive mode and the script mode. The pros and cons of each mode are better explained here. This must have been one of the reasons I couldn't understand why I was asked to import a 'car.py' file yet I hadn't saved any '.py' files before. All this is in reference to Eric Matthes Python Crash Course Chapter 10 on Classess.
On the Python Learning Subreddit, I saw a post from an experienced developer admitting that classes were the most difficult Python item to comprehend and this validated my challenges in understanding this chapter. I like to find a real-life comparison that helps me grasp a concept. Classes, are a tool that stores the properties of an item, for example, making it easy to identify the sanitaryware and joinery in different rooms in a building. A residential unit would have a kitchen, bathroom, office, and bedroom which all have various fittings. To quickly find out the components of each space, you would need a class called Room-default capital letter- which has attributes/parameters using the def function and must reference to the (self) in the class- of the joinery and sanitary fittings that we mentioned.
class Room:
def __init__(self, joinery, sanitary_fittings):
self.joinery = joinery
self.sanitary_fittings = sanitary_fittings
def describe_room(self):
print(f"This room has {self.joinery} and {self.sanitary_fittings}!")
library = Room("timber_cabinets", "ceramic_whb")
library.describe_room()
kitchen = Room("steel_shelves", "stainless_steel_sink")
kitchen.describe_room()
bedroom = Room("mdf_wardrobe", "ceramic_wc")
When you run the code, you expect to see this:
This room has timber_cabinets and ceramic_whb!
This room has steel_shelves and stainless_steel_sink!
I know this doesn't paint a complete picture of how Class works, but I'm writing this under the assumption that the reader has some knowledge of Python. However, if this sparks your curiousry to find out more about the program, then my mission is accomplished!
A webinar from Women Who Code reminded me the best way to test your knowledge is to explain it to someone else. Have I explained the classes well enough or have I missed something? It would be beneficial to hear how other learners mastered this topic.
Comments
Post a Comment