Instance Methods - CS50P Shorts

CS50 · Beginner ·💻 AI-Assisted Coding ·2y ago

Key Takeaways

Introduces instance methods in Python

Full Transcript

Well, hello one and all and welcome to our short on instance methods. Now, we've seen in prior shorts on defining classes and instance variables ways to define some template for some object and ways to instantiate individual instances of those templates to refer to in code and access their various instance variables or traits of each of those individual in this case packages. So, we have here again a class called package that encapsulates some information about packages in general. We say that every package we'll create will have a number like an ID, a sender, a recipient, and a weight to it. And we then define here the various instance variables whenever we create a new instance of this class. Down below on lines 11 and 12, we actually create these instances. We have here on line 11 a package whose number is one, whose sender is Alice, whose recipient is Bob, and whose weight is 10. And then finally down below on line 14, we have some code here that actually accesses the instance variables to print out in a more pretty format um the package information itself. So, let's try running this and see the output down below once more. I'll run python of packages.py and we'll see thanks to the code that we all have here, uh we're able to print information on these packages while still encapsulating and combining the information in a more organized way. Now, it turns out that I can use classes to not just encapsulate or combine pieces of information, but to also encapsulate functionality that I want to be common across all individual packages. I can do so by defining in this case what I might call an instance method. A method that can be run on any instance of this particular class. Now, when I say method here, I'm really referring to particular kind of function that is part of a class. And I'm going to show you one that you might find handy. One called dunder str, dunder stir. So, similar to dunder init, dunder stir is a special instance method that can be called when I when I were to print some package. Now, down below here on line 15, this is a long line of code, but wouldn't it be nice let's say if I could simply print a package like this. Print package and get let's say the same format I have down below. Right now, this will not be the case. If I run python of packages.py, I'll see this. Just not very pretty at all. But I could add an instance method called dunder str to actually improve the output of in this case what I see when I call print on any given instance of my package class. So, let's go back up here and to define some new instance method, well I can simply drop down a line and define some new function that's part of my class. And because this one is a special method defined as some special functionality by Python itself, I'll use these double underscores and then str. In fact, the double underscores which passes as dunder they tend to refer to these special methods that Python attaches a special meaning to. In this case, dunder stir is actually called every time I print every time I call print on an instance of my individual package. So, by convention dunder stir takes as input in this case the in this case the instance of the class itself that we refer to as self. And within dunder stir, I can return some string that will be printed every time I call print on an instance of the package. So, just as a test here, why don't I say um why don't I say this is a package. This is a package. So, every time I call print on a package, hopefully I'll see this is a package. I'll go ahead and run. Go ahead and run python of packages.py and for both of those within my list here this package and this package, we'll see this is a package. Which is helpful, but only a little bit. Like ideally, I'd show some information on the actual instance of the package I'm talking about. So, to do so, I can again access these instance variables and return let's say something like an f-string. It's in the same format we had down below. I could say package again and then self.number colon maybe uh self.sender to self.recipient and then uh comma self.weight uh kg just like this. So, this is the same f-string we had in that for loop, but now I've encapsulated that same f-string inside of my package class within this instance method called dunder stir. Now, ideally when I run python of packages.py, we'll see some more information on this package, but much more simply now we can simply call print package. I'll run this and we'll see that same information now part of some instance method called dunder stir. So, pretty handy here. Now, what else could we actually use instance methods for? We want to maybe attach functionality that seems pretty core to the idea of being a package. Maybe one thing we want packages to be able to do is calculate the cost of shipping them. So, I can imagine here defining another instance method, maybe one called calculate cost that allows a package to figure out how much it cost itself to ship. So, I could here define here maybe a new method called calculate cost. And these instance methods by default again take as input as the first argument the instance itself that we refer to as this variable this argument called self. Now, as another input to calculate cost, maybe the cost changes and maybe a cost per kilogram that I can specify as input to this particular method here. I'll type a colon and within this particular function body, I can then define this instance method called calculate cost. Hm. Let's first see how to use this instance method though. Maybe instead of going down here and just printing the package, I could do something a little more fancy. I could say, why don't we print the package itself as part of this f-string, but then also say that it costs it costs some amount. Now that I have this function called calculate cost that is yet unimplemented, I could use it as follows. For each instance in this case we're calling package in this for loop, I could call calculate cost by typing a dot and then function the actual method name. So, calculate cost. And now as input to calculate cost, could actually type in the input I'm expecting cost per kg. So, I'll say cost per kg and now what we say it's about two US dollars per kilogram to ship some given package. This is how we want to use calculate cost, but now let's implement it up on line 11. Well, I want to make sure to return here the total cost the package. I actually know the cost per kilogram. So, to do that, I think I need to do some simple multiplication. I could maybe find the weight in kilograms and multiply it by the cost per kilogram. So, I could say maybe self self.weight again accessing some instance variable and multiply that by the cost per kilogram. And we'll make the assumption here the user knows that weight should be in kilograms. So, we'll go ahead and say this is calculate cost. It takes the weight in kilograms, multiplies it by the cost per kilogram, and that is the cost of shipping this particular package. So, let's try it down below. Why don't I go ahead and run python of packages.py and now we'll see package one Alice to Bob 10 kg costs 20 and package two costs 10. Probably improve this a little bit. We could simply add a dollar sign here to say this is in US dollars. Run packages.py again and now we'll see some pretty good formatting here. So, this was our brief foray into instance methods. There are some special ones like dunder stir that allows us to say how a instance should be printed as as we saw down below. We can also add some functionality, encapsulate functionality in this case like one to calculate the cost of shipping some given package. This then was our short on instance methods and we'll see you next time.

Original Description

*** This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming. *** HOW TO SUBSCRIBE http://www.youtube.com/subscription_center?add_user=cs50tv HOW TO TAKE CS50 edX: https://cs50.edx.org/ Harvard Extension School: https://cs50.harvard.edu/extension Harvard Summer School: https://cs50.harvard.edu/summer OpenCourseWare: https://cs50.harvard.edu/x HOW TO JOIN CS50 COMMUNITIES Discord: https://discord.gg/cs50 Ed: https://cs50.edx.org/ed Facebook Group: https://www.facebook.com/groups/cs50/ Faceboook Page: https://www.facebook.com/cs50/ GitHub: https://github.com/cs50 Gitter: https://gitter.im/cs50/x Instagram: https://instagram.com/cs50 LinkedIn Group: https://www.linkedin.com/groups/7437240/ LinkedIn Page: https://www.linkedin.com/school/cs50/ Medium: https://cs50.medium.com/ Quora: https://www.quora.com/topic/CS50 Reddit: https://www.reddit.com/r/cs50/ Slack: https://cs50.edx.org/slack Snapchat: https://www.snapchat.com/add/cs50 SoundCloud: https://soundcloud.com/cs50 Stack Exchange: https://cs50.stackexchange.com/ Telegram: https://t.me/cs50x Threads: https://www.threads.net/@cs50 TikTok: https://www.tiktok.com/@cs50 Twitter: https://twitter.com/cs50 Twitter Community: https://twitter.com/i/communities/1722308663522594923 YouTube: http://www.youtube.com/cs50 HOW TO FOLLOW DAVID J. MALAN Facebook: https://www.facebook.com/dmalan GitHub: https://github.com/dmalan Instagram: https://www.instagram.com/davidjmalan/ LinkedIn: https://www.linkedin.com/in/malan/ Quora: https://www.quora.com/profile/David-J-Malan Threads: https://www.threads.net/@davidjmalan TikTok: https://www.tiktok.com/@davidjmalan Twitter: https://twitter.com/davidjmalan *** CS50 SHOP https://cs50.harvardshop.com/ *** LICENSE CC BY-NC-SA 4.0 Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License https://creativecommons.org/licenses/by-nc-sa/4.0/ David J. Malan https://cs.harvard.edu/malan m
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from CS50 · CS50 · 0 of 60

← Previous Next →
1 Hello, World: Hadi Partovi
Hello, World: Hadi Partovi
CS50
2 Content Distribution and Archival in a Digital Age
Content Distribution and Archival in a Digital Age
CS50
3 CS50 2014 - Week 1
CS50 2014 - Week 1
CS50
4 CS50 2014 - Week 3
CS50 2014 - Week 3
CS50
5 CS50 2014 - Week 0, continued
CS50 2014 - Week 0, continued
CS50
6 CS50 2014 - Week 4
CS50 2014 - Week 4
CS50
7 Week 3, continued
Week 3, continued
CS50
8 Quiz 0 Review
Quiz 0 Review
CS50
9 CS50 2014 - Week 3, continued
CS50 2014 - Week 3, continued
CS50
10 CS50 2014 - Week 7
CS50 2014 - Week 7
CS50
11 CS50 2014 - Week 7, continued
CS50 2014 - Week 7, continued
CS50
12 Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
13 Introduction to Amazon Web Services by Leo Zhadanovsky
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
14 CS50 2014 - Week 9
CS50 2014 - Week 9
CS50
15 How to Build Innovative Technologies by Abby Fichtner
How to Build Innovative Technologies by Abby Fichtner
CS50
16 Light Your World (with Hue Bulbs) by Dan Bradley
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
17 Building Dynamic Web Apps with Laravel by Eric Ouyang
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
18 CS50 2014 - CS50 Lecture by Steve Ballmer
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
19 CS50 2014 - Week 10
CS50 2014 - Week 10
CS50
20 This is CS50 with Steve Ballmer?
This is CS50 with Steve Ballmer?
CS50
21 Meteor: a better way to build apps by Roger Zurawicki
Meteor: a better way to build apps by Roger Zurawicki
CS50
22 Data Analysis in R by Dustin Tran
Data Analysis in R by Dustin Tran
CS50
23 Data Visualization and D3 by David Chouinard
Data Visualization and D3 by David Chouinard
CS50
24 CS50 2014 - Week 6
CS50 2014 - Week 6
CS50
25 Build Tomorrow's Library by Jeffrey Licht
Build Tomorrow's Library by Jeffrey Licht
CS50
26 CS50 2014 - Week 9, continued
CS50 2014 - Week 9, continued
CS50
27 Essential Scale-Out Computing by James Cuff
Essential Scale-Out Computing by James Cuff
CS50
28 iOS App Development with Swift by Dan Armendariz
iOS App Development with Swift by Dan Armendariz
CS50
29 Sam Clark Leads Yale Students on Tour to CS50 at Harvard
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
30 3D Modeling and Manufacture by Ansel Duff
3D Modeling and Manufacture by Ansel Duff
CS50
31 CS50 2014 - Week 5, continued
CS50 2014 - Week 5, continued
CS50
32 hello, world
hello, world
CS50
33 CS50 2014 - Deep Thoughts - Hash Table
CS50 2014 - Deep Thoughts - Hash Table
CS50
34 CS50 2014 - Deep Thoughts - Binary Tree
CS50 2014 - Deep Thoughts - Binary Tree
CS50
35 CS50 2014 - Deep Thoughts - Scratch
CS50 2014 - Deep Thoughts - Scratch
CS50
36 CS50 2014 - Deep Thoughts - MySQL
CS50 2014 - Deep Thoughts - MySQL
CS50
37 LaunchCode Visits CS50
LaunchCode Visits CS50
CS50
38 CS50 Live, Episode 100
CS50 Live, Episode 100
CS50
39 CS50 Field Trip to Google
CS50 Field Trip to Google
CS50
40 This is CS50 AP
This is CS50 AP
CS50
41 Week 4: Monday - CS50 2011 - Harvard University
Week 4: Monday - CS50 2011 - Harvard University
CS50
42 Week 2: Wednesday - CS50 2011 - Harvard University
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
43 Week 1: Wednesday - CS50 2011 - Harvard University
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
44 Week 11: Monday - CS50 2011 - Harvard University
Week 11: Monday - CS50 2011 - Harvard University
CS50
45 Week 3: Wednesday - CS50 2011 - Harvard University
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
46 Week 12: Monday - CS50 2011 - Harvard University
Week 12: Monday - CS50 2011 - Harvard University
CS50
47 Week 1: Friday - CS50 2011 - Harvard University
Week 1: Friday - CS50 2011 - Harvard University
CS50
48 Week 3: Monday - CS50 2011 - Harvard University
Week 3: Monday - CS50 2011 - Harvard University
CS50
49 Week 10: Wednesday - CS50 2011 - Harvard University
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
50 Week 2: Monday - CS50 2011 - Harvard University
Week 2: Monday - CS50 2011 - Harvard University
CS50
51 Week 9: Monday - CS50 2011 - Harvard University
Week 9: Monday - CS50 2011 - Harvard University
CS50
52 Week 7: Monday - CS50 2011 - Harvard University
Week 7: Monday - CS50 2011 - Harvard University
CS50
53 Week 5: Monday - CS50 2011 - Harvard University
Week 5: Monday - CS50 2011 - Harvard University
CS50
54 Week 5: Wednesday - CS50 2011 - Harvard University
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
55 Week 7: Wednesday - CS50 2011 - Harvard University
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
56 Week 8: Monday - CS50 2011 - Harvard University
Week 8: Monday - CS50 2011 - Harvard University
CS50
57 Week 9: Wednesday - CS50 2011 - Harvard University
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
58 Week 8: Wednesday - CS50 2011 - Harvard University
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
59 Week 10: Monday - CS50 2011 - Harvard University
Week 10: Monday - CS50 2011 - Harvard University
CS50
60 Week 2: Wednesday - CS50 2010 - Harvard University
Week 2: Wednesday - CS50 2010 - Harvard University
CS50

Related Reads

Up next
Copilot Cowork: Setup, Skills, Plugins & Pricing
Matt Tutorials
Watch →