Building With Classes Practice: Python Basics Exercises
Key Takeaways
This video course preview covers Python Basics Exercises, focusing on building systems with classes, object-oriented programming, and practical programming tasks using Python and IDLE.
Full Transcript
welcome to this real python exercises course where you'll practice Building Systems with classes our exercise courses are all about training you'll train the process of writing code by solving carefully selected exercises you'll also train reading other people's code and communicating your thought process doing all that you'll practice the concepts that you've learned about in an Associated course or tutorial and help make them stick in the upcoming lessons I'll introduce to tasks give you an opportunity to solve them yourself and then show you step by step how I solved each of them so you'll go through three steps for each task you learn about the exercise you'll code your own solution and then you'll compare Your solution and the process that got you there to mine when I walk you through a task I'll explain what I do and also why I do it like that that'll give you a chance to compare not just our final Solutions but also how we got there ideally this can help you gain some insight on the process of getting from a task description to a working solution in code you'll start by solving some review exercises in the first section of the course and build up towards a challenge in the second section you'll actually train Building Systems with classes in Python the challenge in this course will be quite big and open-ended it'll give you a chance to revisit fundamental oop Concepts inheritance composition and how to make it all fit together to build something meaningful because the challenge is quite big and it took a lot of lessons when I wrote the code you'll see a third section in this course there'll be a continuation of the challenge that you'll start at the beginning of section two don't pick ahead okay so now the big question are you ready for this course the idea for this exercises course is that you should have watched the python Basics course on Building Systems with classes before starting this one if you went through that course then you're well equipped to solve the tasks that you're about to encounter the concepts that you should have heard about and will practice are python classes attributes and methods so that's class attributes and instance attributes instance methods special methods Etc and FST strings if you're already somewhat familiar with these Concepts but you want to fortify your knowledge with practical programming tasks then this course is exactly right for you before we get started there's another tiny bit of background for this course which is that I'll use idle the integrated development and learning environment that comes with python if you've gone through the python BAS courses then you're already familiar with the tool if not and you want to know more then you can check out these Associated courses that cover getting started with idle I'll use idle's interactive console that gives you direct access to the code defined in the python file you executed this makes it a bit more interactive when testing your code but you don't need to use that feature and you can replace it with print calls at the end of your file so if you're here to train outside of the Python Basics courses feel free to use whatever tool you like to solve the upcoming coding tasks and that's all there is to say to get you set up if you're ready to get started and do Hands-On programming then see you in the next lesson there you'll get to know the first review exercise which as you can see from this Immaculate modeling code will be your entry point before we crank up the difficulty well Crank It Up One Step but what do numbers in isolation mean at all how many levels are there two 100 wait am I questioning the class system I built here let's start this off by taking a quick walk through the doc class just so that you remember what is this doc class that you're going to be working with in this review exercise this is the same dog class that you built in the python Basics course that these review exercises are for that's the code I'm going to head over to the idle repple here are I have the code saved and I will run the code in idle using F5 and now I'm over here in the interactive repple and I can play around with this dog class let's start by creating one instance I'm going to call this one wolf and wolf is a dog with the name wolf and it's a puppy he's only a year old so here I'm creating an instance of the dog class by passing in a name and an AG this is what's required according to the initializer method once I execute that I have my dog object and I can print it to get a nicer representation of what this whole object is about wolf is one years old so I get the name and the age of the dog and then you also have access to a class attribute called species which points to the string canis lupus familiaris which is the scientific name for a dog and to be precise it's actually a subsp species not a species because canis lupus is the gry wolf and all dogs are just subspecies of gry wolf but this approximation shouldn't hurt anyone I can also access this class attribute through the instance I can say wolf. species and it gives me canis lupus familiaris not that this is a class attribute so you can also access it through the class I can say do. species and get the class attribute and that's generally the better way to access a class attribute because if I would set this wolf. species to something I would create a new instance attribute and override the class attribute basically but let's not go into this too much for now we're just taking a walk through the dog class right one more thing we can do with wolf is we can ask wolf to speak and say what does wolf say wolf and then we can see that wolf says wolf so in this doc class you have one class attribute you have an initializer method that defines that you need to pass a name and an AG to when you instantiate the dog and these two get assigned to the instance then you also have a Dunder string method defined which gives you a readable representation when you print a dog object and then you have one more instance method that is called speak and this one takes as an attribute of sound and then returns a string that really just says the name of the dog and what sound they say this is the parent dog class that you're going to be working with in the next review exercise I hope you enjoyed that walk through the dog park and see you over in the next lesson where I get started with the exercises here's your first review exercise create a child class a golden retriever class that inherits from the doc class and you use the following code for your parent doc class that's the code that you've just explored in the previous lesson use this do class basically as a parent class to create a child class called Golden Retriever we don't have any more instructions on what this child class should do so for now it's enough if you just create an empty child class that inherits from the dark class that might be a quick one go ahead and solve the task and then move over to the next lesson and I'll do it there as well to create a child class from a class what do you need to do is again use the class keyword then type in the name of your class so Golden Retriever and then you can open up parentheses here and then put in the parent class and then close to parenthesis and finish it off with a colum as usual in the next line I'm going to for now put a pass keyword just to satisfy Python's need for some indented code after a column but I'm not going to implement any functionality in the child class so far that's really all you need to do to create a child class after the name of the child class you have to put the name of the parent class in parenthesis that's it and now golden retriever has all the functionality that the doc class has as well as all the attributes so we can try that out I'm going to run the code and jump over in the interactive shell and now I'm going to make a golden retriever we call them Bu The Golden Retriever and again it needs a name and the H we already called them buddy so let's stick with that it's an old dog 12 years old no complaints so now I have an instance of golden retriever here you can also see that if I print the representation of Budd then it says in the main Nam space I have a golden retriever object at a certain memory location great and what can budy do budy can speak I can print body so the dunder string also gets taken over from the parent class so the same format you can also access the class attribute by the through the instance do what's it called species and you can see that it's still a dog all right so with this short two lines of code you created a child class that inherits from the dog parent class let's see what else we can do to review everything that you've learned in the associated course your second review exercise asks you to extend a method from the parent class give the sound argument of golden retriever dope a default value of bark the string bark and again you're going to use the same dog class as your parent class what you're going to need to do here is to work with method overwriting or extending so you want to do something with the speak method from the dog parent class and you can see that it takes a sound as an argument and you want to provide a default argument for Golden Retrievers so the child class called Golden Retriever should have a default argument that the parent dog class doesn't have so that if you don't pass anything to do speak on a golden retriever object then it should always say bark okay that's the task try it out and then move on to the next lesson where we'll code up a solution together your task was to provide a default value of bark for the doe method what you're going to need to do here is to define a speak method in the golden R class this is going to overwrite the speak method from the parent class so if I say def speak self sound here then this is going to overwrite the method that is defined in the doc class because it has the same name you don't really want to overwrite it you just want to augment it you want to extend it with this default argument first of all let's see how we can create a default argument in Python that is by using equal sign here and then passing that default value to the argument I'm going to say this is bark and now I don't want to Define this return string another time I want to keep using the one from the parro method and in order to do that I need to actually reference the method on the parent class inside of my speak method in the child class and I can do that by saying super that gives me access to the parent class and then I'm going to call the doe method from the parent class and I will pass it the sound and this again is going to be whatever sound you pass in when calling speak on a golden retriever object but if you don't pass in any sound then it'll use the default value of Mark that you defined here just calling it like that is not enough you would also need to return this so I'm going to add a return statement here and with that that should be it I think we're done let's test it out I'm gonna run the script and go into the interactive mode in the repple and now let's create another golden retriever I'm just going to copy the code I used before and we'll work with Buddy again and now I should still be able to say buddy dope and pass it a string so for example I'm going to say buddy. speak and then pass it wow and budy says wow but now if I'm going to call speak on body without passing an argument then it should default to bar like I defined in the speak method on the golden retriever class and it's working body says bark so what I did here is I extended the speak method of the parent class by providing a default argument to sound and it's an extension of the parent class method because you're calling the method in the body of your speak method in the chat class if you wouldn't call it then you would effectively override the method from the parent class with a new method all right task done let's do a quick recap on this review exercises and then head off to our challenge before moving on here's a quick recap of what you practiced in this review exercises there were some quite quick ones but you still get a chance to build a child class and inherit from a parent class extend and instance method from the parent class in your child class and you also practice providing a default argument which isn't specific to classes in Python but that's just the way you do it and doesn't hurt your practice anyways you also might have picked up a couple of tips that help you develop in general specifically you saw me use code comments to help you get organized that's something I always do and I find very helpful and also to test your code so to actually figure out whether what you just implemented does what you expect it to do that's it for the review exercises next up is going to be a challenge don't worry you can do it your challenge is to create a simplified model of a farm also keep in mind that there's many correct answers so this is not going to be an exact solution but there's going to be a lot of different solutions that are all correct there are specific requirements that you can use as a guideline keep in mind that they're open to interpretation you should have at least four classes the parent animal class and at least three child classes that inherit from animal each of those classes should have a few attributes and at least one method that model some Behavior appropriate for a specific animal or for all animals so that could be walking running eating sleeping or something that only I don't know a horse would do keep it simple utilize inheritance make sure you output details about the animals and their behaviors this is part one but we have a second slide here we go continue modeling your Farm you want to create two more classes maybe a field and maybe a barn and these places should have an attribute where they can store animal objects so here you're going into the direction of composition imagine the day today on a farm you may want to move a cow from a field into the barn can you do that what's the methods that you need to be able to move the cow which data structure is going to hold the cow on the field or in the barn how many can fit into a barn maybe you want to continue maybe you feed the animals with other classes that could represent Foods maybe there's like this level of hunger level of enjoyment that gets modified when you feed them get creative with this idea but also don't get carried away too much it's just a model the focus of this assignment is less about the class syntax which you've already trained before in the review exercises but it's about software design in general and again this is highly subjective so it's intentionally left open-ended so that you get a chance to to think about how you would organize your code into classes this course is also there to give you a chance to see how someone else would do it this whole thing makes me very happy because it's highly subjective which means I can just go ahead and code something up and it's not really going to be wrong there will be many solutions Your solution is very likely going to look different from mine but it doesn't mean that it's wrong and overall this gives us lots of chances to learn from each other why did you code something in a certain way why did I code it in a certain way and there's this chance to compare and that's what this whole challenge is about try out your way of doing something and then compare it to someone else's expect mistakes expect opinionated decisions and hopefully discussions in the discussion tab if you don't understand why I did something a certain way or you think that there's a better way to do it or just a different way that you like more post about it show your code and then we can talk about it and with that I have one more thing for you a very important tip sketch it out before you start programming I actually mean draw it by hand now you can take pen and paper or you can use a digital tool it doesn't really matter what material you use the important thing is that you use your hands and that you can iterate over it often draw out your image of the code that you want to build and I mean do that before you actually write any code so grab a pen and paper sketch out a model of your farm identify what classes you want to build which attributes they should have and which methods they should have think about inheritance that can help you to prevent code duplication and do this as often as you need before actually starting to code just until you have a good mental model of what that farm abstraction is going to look like because it costs a lot less energy to just draw a circle or a square and write a word there then to actually build that class if you do that beforehand it just sorts your brain and gets you a mental model of the code that you're actually going to build which is super helpful and it's going to make your developing experience much nicer so do that first draw the idea of the farm that you want to model and only start coding afterwards I'll also sketch my idea on digital paper in the next lesson when you're done sketching and coding your own Farm then continue with the next lesson and start to compare Your solution and your process to M have fun and see you there
Original Description
This is a preview of Python Basics Exercises: Building Systems With Classes video course. Time to move beyond the basics of object-oriented programming (OOP), and start to put those classes to work. In this preview of the exercise course you'll employ these capabilities to build more complex systems and write readable, reusable code.
This is a portion of the complete course, which you can find here:
https://realpython.com/courses/building-systems-classes-exercises/
The rest of the course covers:
- Inherit and override behavior from other classes to create variations
- Creatively mix and match these approaches
- Instantiate classes with attributes and methods
- Override methods from a parent class
- Practice by modeling a farm with classes
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: LLM Foundations
View skill →Related Reads
📰
📰
📰
📰
I built an open-source internship tracker that polls 3,593 company career feeds
Dev.to AI
Meta Just Realized Owning GPUs Is Not a Strategy
Medium · Programming
Daily Crypto Update: VishvaAlgoAI Finds 9 Long, 5 Short and 6 Neutral Verdicts
Medium · AI
How AI Is Changing Self-Publishing in 2026
Medium · AI
🎓
Tutor Explanation
DeepCamp AI