OBJECT-ORIENTED PROGRAMMING IN PYTHON - CS50 on Twitch, EP. 33

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello world this is cs50 on twitch my name is Colton Ogden I'm joined today by brain you who has been on stream before so previously we talked about react and normally we build something from scratch but sometimes you do conceptual discussions so what are we talking about today today the topic is going to be object-oriented programming which is a programming paradigm that you'll find in a number of different languages today in particular we're going to be looking at Python though there's object-oriented programming in languages like Java for instance and many other languages as well are beginning to use this paradigm and it's quite popular in the programming world down so C so cs50 what what we what do we sort of teach in cs50 and how does object-oriented programming sort of compare and contrast to that yeah so the style or programming paradigms in cs50 talks about is this idea of what we might call imperative programming and what object-oriented programming is it's a slightly different take where the focus is about trying to model real-world things as what we might call objects and those objects are gonna have two parts to them objects might have some data associated with them so you might have an object that represents like a shopping item for instance and in a store and that item has a name it has a price and I have an image associated with it for instance and those objects can also have some code associated with them code that you can use to operate on or manipulate those objects so you might have a way to purchase a shopping item for instance might be some code some action it's associated with that particular object you can use to make something happen click them kind of taking it above the sort of bare metal of the computer a little bit more than something like C where you're literally coding instructions that kind of roughly mapped how the CPU talks in a sense yeah exactly it's an often a feature of higher level programming languages that allow you to reason a little bit more abstract lis allow you to organize code in particular ways we're gonna be able to write code that we probably could write in an imperative way you think cs50 style programming but this is just going to offer a slightly different way of achieving the same thing and it's ultimately going to allow for a more clean way of running certain types of code cool and then we're will be using Python today Python being one of the more popular languages currently in use but this is a paradigm that we see all over the place and particularly Java some folks in our community might be familiar with Java and Java is a very very object focused language where you literally everything has to be an object in in Java let me go ahead if you're ready I can switch over to your computer if you want yeah sure we'll go ahead and guess on our trip to object oriented program all right there we go oh sorry the screen we've got a little bit glitch there go ahead you can keep going on with this stretch the screen matches all right sounds good not sure how that happened there we go perfect all right so I have here a terminal window and what I thought we'd do is just has a bit of an introduction to Python now I'll just go ahead and type Python we're just going to open up a Python interpreter I'm using Python version 3.7 but any version 3 or later will probably be sufficient for the sorts of syntax that we're going to see today and in this Python interpreter I can begin to type value the names of expressions or values and I can see what they're equal to so the number I typed it number 50 for instance and what I get back from the interpreter is okay this is the value 50 and of course that's obvious because I typed in the number 50 exactly but you can type more complex expressions right I could type an expression like 20 plus 8 and when I get back is not literally 20 plus 8 but I get that expression which gets evaluator to a value and that value in this case is 28 for instance and so this 28 here it's a number in particular it's an integer and if I type in the number 28 okay its value is 28 but there's a special function in Python called type which I can use if I say type 28 for instance I can say all right what is type and here we see the first instance of an object oriented programming word this word class class is going to tell me sort of what type of information is this value the number 28 is telling me belongs to a class called int and so the way to think about this is 28 is an object if it's a thing that exists is a value in Python and it belongs to a class what type of thing is 28 well 28 in this case is an int + int happens to be one of the built-in classes in Python that I can use and in fact anytime you use an integer in Python you're using an object that is of this int class being more of a dynamic language it doesn't really have technically speaking the same kinds of primitives that like seaward you know even Java which adamantium did mention the chat saying that he uses Java does that primitive so that everything is an object I should clarify what I meant was everything is wrapped in an object for example you can't read a main function without it being in a class I'm not an object at class I should say everything is wrapped in a class but in Python there aren't there really isn't technically speaking the idea of a primitive at least in terms of you know this is 32-bit 32 bits and that's it you know we have a wrapped in some extra packaging yeah so all of the even this basic integer 28 has some data and code associated with it that are normal with just a pure integer wouldn't have so I could call 28 like dot so let's see what the options are oh sure I can do 28 dot numerator for example and say that didn't work if I said X equal to 28 I can say X dot numerator and okay I get the numerator of 28 is just 28 and the denominator of 28 is 1 for instance and that's not something you could do if we just had the literal bits representing the number 28 it only works because this variable X is what we might call an instance of the int class and when I say instance I just mean that if int is a class then anytime I have an object that belongs to that class that's going to be an instance of the class so X in this case is an instance of this int class so like class being the blueprint and then the actual 28 is the physical thing sort of we want to take it you know into a physical analogy the physical thing we use the blueprint to create or construct exactly yeah and ant is not the only class that's built into Python if I have the string hello for instance I'll have that equal to I'll just call it s4 string right so I have this variable called s and if I take the type of s I see that s belongs to a class called stir it is an instance of this class stir wear stirs distort short for string for instance and there are all sorts of functions that we have that are associated with objects that are an instance of the stare class so for instance capitalize is one that just takes a string and capitalizes the lowercase H turned into a capital H for example and so that's an example of yet another class that we have that's built into the Python program you all have this nice functionality for free and this is a nice thing to what you mentioned earlier is that these classes allow us to sort of tie this functionality to different data types to allow us don't have to write functions for every single things separate from the data it's kind of all packaged together yeah exactly so we have these built-in classes int ster and their number of others but what I thought we'd do today is show you how you can using the syntax of object-oriented programming in Java or in Python rather create your own classes that have their own data that behave in their own particular way is it because there are a lot of built-in classes in Python but there are certainly types of things that we might want to model that we might want to represent using data and code for which there don't exist classes in Python already sure what we can do is we can write some classes of our own that we can then use in order to create some functionality of our own so I thought we'd do if I go ahead and open up a text editor here I noticed by the way you are an atom user before and recently you've been using vyas could have you made that have you made this suite permanently yeah I switch our own text editors from time to time I use the atom for a time I use sublime text for awhile I've been using the S code lately as well sometimes I'll just use vim built yeah Babic Knight knows that I use them often so you'll often see me using that as well in particular in like the web programming class I think I used them for some portion of that as well so it varies but at the moment BS code seems to work pretty well as a quick aside what have you found any features of the S code that you like relative to atom or vice versa things that it's lacking that atom has one really nice feature of atom that they introduced actually recently within the past year or so is the ability to do live Google Doc style collaboration on a text file so that if I'm on atom and I want to collaborate on a piece of code with my partner I can sign in with my github username and my partner with his or her github username and we can just be working on the same file typing live seeing each other's changes at the same time that I think is a very compelling feature of Adam it's very useful for pair programming for working collaboratively but I haven't really seen anyone quite be able to replicate in any unlike that I'm I'm kind of disappointed Fiasco doesn't yeah it was unfortunate it would be nice of it did a matter of time I think yeah maybe soon maybe it will see apparently Visual Studio Live cher does the same thing for vs Co interesting I'm not familiar with that but it's possible that there are extensions that you can add these text editors that give them those features all of the big texts that are just nowadays vs code sublime text Adam and many others have so many third-party packages that you can install that add a variety of different features to the application and so finding the right packages can definitely be an important part of picking the right text editor it's cool okay what I'll do here is what I thought we'd do is create a class that's going to represent like a book for instance a book that has a title and an author for instance and maybe other data associated with it as well so I'm going to go ahead and save this inside of a file that I'll call book PI and what I'm going to do is I'm going to create a new class remember the class is the type of object that we're going to be creating I'm not right now gonna be creating a specific book I'm gonna do be defining the syntax for a class that it's going to allow me to create as many books as I want based off of this class definition based off this blueprint for what it is that a book is so I'll say class book and this is my way in Python of defining some brand new class and the first thing that I need to do when I create a class is define some sort of function for what should happen when I try to what's called instantiate this class when I try to create a book what should happen and in Python this function has a little bit of a cryptic name it's called underscore underscore init underscore underscore in it standing for initialize and Python often makes it special functions or special methods have two underscores on either side of it so it's just a Python convention and so in it is going to be a function that's going to create a new book and whenever we have particular functions that are going to run on objects on objects that belong to a class we're generally going to call these methods instead of functions it's just part of the syntax of the language of object-oriented programming the generally functions that operate on objects we call methods but effectively you can think of them as like functions and this init function all of the methods that operate on objects in Python will have this argument called self which is a little bit strange at first but basically self just refers is a way of naming the object that we're working with that we might be creating five ten twenty different books and we want to be able to reference the data inside of each individual book and self is going to be a variable that is always going to refer to the book that we're currently dealing with okay make sense so then when I create a new book what are the types of information that I want to associate with the book so this is the question like when I create a book what goes into the book well probably at minimum we need a title for instance and so I'm adding this title argument to the init function remember this init function is the code that is going to run when I try to create a book and here I'm saying when I create a book the book itself is going to be called self but I also want to provide some additional information when I create the book I want to tell the book what its title is going to be okay makes sense so this will go into the parentheses when we create a new book in our code exactly and we'll show that in just a moment and so now inside the code of this init method when I create a book I want to store inside of the book inside of this self object I want to store the title and so what I can do is in any object you can assign values to properties of that object using dot notation in Python where I can say self dot and then the name of some property I can the self dot property name or property name could be anything and give it some value where that value could also be any Python value for example and in this case the name of the property is just going to be title I want to change the name of the property in the book called title to be equal to whatever this title argument is and so a common paradigm when you're creating objects is to say well let's pass in the title when you first create the book and then what do I do with that title well I set it to be equal to self duck title in other words I take the self object the book that I've just created it modify its title attribute and set it equal to the argument that I've passed in right so a lot of syntax so far some of which may be a little bit unfamiliar but long story short all we've done here is to find a blueprint for how to create a book I create a book by providing a title and that's going to store the title inside of the book write the dot being probably the most the newest thing for a lot of people and a lot of people might have used a module in Python or imported a you know part of the standard library or something and used it there but I'd actually seen it you know in the context of creating a class themselves or yeah yeah yeah in the same way that we had like the number before or is it where I was able to say that number dot numerator or got denominator that's the same idea of accessing a property of the object where the object stores a whole bunch of data and a whole bunch of code with it and if I want to access the data associated with an object I just reference it by the name of that property self dot title in this case makes sense I'm going to say there why not use the properties like title inside the class assigned to a variable such as class assigned to a misery they're probably referring to a what would get static variable in this case okay we might touch all in the static variable is a little bit later or Python will generally call them like class variables I guess this would be a good point to bring up and maybe they're saying why not just create a new variable in here why do we have to call it self dot title when are you sure you could imagine that we could just call a variable t set it equal the title for instance but remember that if you define a variable inside of a function when that function is done running we lose access to the variable so immediately after this init function is done running this T variable is no longer going to exist we can see that if I do something like I'll define a function called F and what F is going to do is set X equal to 10 for example if I run the function f and then I say okay what is X like I say print X to see what is the value of x I get a name inner write X is not defined even though I called F which the value of X up here after the function was done executing I lost access to that variable X because it's its scope so to speak is local to that particular function so after the function is done running I no longer have access to this X the same thing is going to be true of this variable title this is just a variable inside of this function and so if I don't do anything as soon as this function is done running I'm going to lose access to that variable we might want to say you know whatever book dot title later right if I want to be able to access the title later after I've created the book I need to store it inside of the self object somewhere that information is going to stick around even after the functions done running because the object still exists and so I'm storing it inside of self title so that I can keep it and then bihari was asking that why shouldn't the first argument of an it just be self the first argument yes the first argument of in it should be self and it could be the only argument but you're also allowed to have other arguments too in it as well there are other information that you want to provide when you are creating a book for instance I mean then Jack OTS is asking so the word self has the same function as the word this for instance in JavaScript just asking not familiar with Python yeah exactly you can compare itself in this case is very similar to this in JavaScript or other languages just some word that represents the current object okay so now let's go ahead and try and use this let's try and create a book so I'll go ahead and type Python and right now the keyword book right book is not defined this is not something that's built into the Python language specifically it's defined inside of this file book pi and so I want to import from this Python file from this module the book class and so the syntax in Python to do that is to say from book that's the name of the module book PI that I want to import the class from let me import this book class capital B and all right now I've imported the book class if I type book all right this is a class and it's called book for instance essentially extended the language and in a way we now have new yeah we have access to a new class a new noun that we didn't have access to before because we've just created this so if I want to create a new book I'll call it B will say B equals book and then the argument to book is going to be the title the name of the book that I want to create and your favorite book it's been a while Harry Potter I guess Harry Potter will go Harry Potter it will do and the Sorcerer's Stone which which one was your favorite Harry Potter book favorite Harry Potter book I'm a tough woman it is a tough one I was quite a fan of the fourth book the Goblet of Fire I thought was very you know but they're they're all they're all quite excellent so we recommend them if you haven't read all right so I'm creating a new book and in the parentheses I'm providing the title the argument someone likes half-blood Prince also a very good book yeah providing is an argument to book the title of the book that I want to create and I'm saving that book inside of a variable called B I press return and right I've created this variable called B B is a book object and in particular if I say what is the type of B what I get is alright B is a book and in particular I can now access the properties of this book if I want to get the title of the book I can say B dot title for instance and alright I get Harry Potter and the Sorcerer's Stone and what might clarify I don't know if you might already mentioned this hypothesis if you did but this self is implicit in on line three you're we're not ever passing in self to the constructor for the class and so somebody maybe I could I can envision maybe somebody saying what we're calling book but it's only taking in a one string Harry Potter the Sorcerer's Stone but my line three and book has two arguments to the function like what's going on yeah so it's a good question and an easy area for confusion in Python because it is one of the little strange quirks or nuances of Python there have been a lot of discussion and debate about whether that's the right way to do things but pythons Creator has long defended this is the ideal way to do it in the Python programming language and there are good reasons for it but the idea here is that this self argument to the init method is not one that I provided when I created a new book it's just going to be automatically inserted by the Python interpreter it knows what self is and that's always going to be the first argument and I just need to provide the arguments that come after it all right the other question the cake in 1990 was asking can you briefly touch on private variables and classes in Python yes so this is a distinction between Python and languages like Java for instance where in Java you get to have a lot more control over what types of things are public and what types of things are private notice that there is no notion of like adding public or private to the variables here in Python just a bit of a difference between the attributes that we define in Python and in Java and so the types of things that you can do with classes end up being a little bit different as a result are there some conventions maybe that we could use to kind of simulate private variables and functions yeah a common convention in Python is if an attribute starts with an underscore those attributes should be considered private and if you're using the class you shouldn't directly try to access those properties that begin with an underscore you don't technically need to follow that rule from a language perspective the language doesn't enforce it but it is a convention of the language oh it's the sort of on the programmer it's right and follow the conventions Python gives the programmer a lot of power in that respect sham X are no need for self in the objects yet what Brian just said self as implicitly passed in by the interpreter Oh class is returning as book book object but it classes are turning actual integer is there a way in a class to return what you want it says enter ready five can you clarify what you mean by that question so the B the B variable itself right now represents this book or it is a variable inside of which we're storing this book object and that book object is exactly what I've created in this blueprint it is an object that contains within it a title property whereby I can access the title of the book so I can say beat out title to get the title of the book there may be they were confused as to the fact that you can just type in the number 23 and it just works like a number but with book you know you're getting this sort of like construction that you've put together with a title and whatnot it doesn't have I guess maybe amorphous behavior more of this polymorphic behavior depending on the data type but it may may actually be the case that Python special cases like integer and stuff so that you can use them as because it's part of the grammar for the language like numbers so what do you mean you so you won't be able to like if you try and add a book to a number for instance that's not going to work thank you for it you couldn't theoretically define your own class that works like a number because Python special cases you might be able to so you can there are other properties you can add to these classes that allow you to get it to behave in particular ways it's like comparing whether a thing is less than another changing the way that it responds to particular operators so that we can get a lot more sophisticated than we've gotten so far in terms of the lexical parsing they like the fact that you can use like 23 as a literal oh the 23 literal yeah that specifically creates an int object and that's I imagine that's probably something that I don't know if we can get that kind of flexible a flexible behavior such that we could lexically special case new data cuts yeah as far as I know there's no way to do that in Python though if someone knows of a way so I think I think that's probably what they're referring to it but if I interpreted that incorrectly please let me know and let me make sure we didn't miss any other good questions here and it's the constructor yeah the name of this method is just called a constructor because it's the code that we use to construct a new object in Java you typically declare us as adamantine you typically declare all the attributes that are used in the class is this done in Python or is that just done in the constructor oh great question so in Java you're probably used to saying all right let's define all the properties of the class upfront and so if there's a title for the book and an author for the book you define all that at the beginning not necessarily the case in Python if I right now this book only has a title and the constructor only set a title but if I wanted to set the author of this book I could say be doc author equals JK rowling for instance just in with Harry potter-themed that's the same book so still be so be title is Harry Potter in the surgeon of stone and be taught author is JK Rowling so totally something that I can do is well here without needing to have it as a property that's actually defined inside of the book class cool we just make sure we got everything jumped up wondered am i late no we're still pretty early what do you guys do so Brian you're an undergrad yeah I am a technologist under the hood oh can you uh the cake 1990s asking can you show us how we can define operator overloading classes oh yeah gets a little bit tricky I want to make sure that we stick with the fundamentals at least for now if we have time if we have time we might be able to touch on some of that stuff yeah some of the more advanced and then last two questions are you obligated to determine the type of the property for example I need the title to be only a string you so Python has dynamic typing meaning we don't enforce the type of the property so bita title right now is a string and if I change B title to be like a floating-point number like even though it doesn't really make sense to do that you could do it there are ways of trying to protect against this you can add some special code to your classes and say when I try to set the value of a property you should run this code that maybe add some type checking of your own to make sure that it is in fact a string but those are so those features are available but not part of the most simplistic way that we could create a class in Python and so one of the things you'll notice about Python is it tries to make the syntax for creating a new class creating a new object as simple as possible such that for the vast majority of use cases you can stick with the simpler syntax but if you want more specific feature it's like the ability to validate the types of attributes and the ability to overload operators for instance those are things that you can get but those require a little more sophistication in the definition of the class okay and then lastly can we override the constructor or or it's just like the constructor with the default parameter I guess in a nutshell can't we override the constructor yes so the general way you do something like that in Python is if I wanted to say allow for me to create a book that has a title but maybe I also want to be allow a book to have an author as well so I can add an author argument to the init function and then say like South author equals author and now if I go ahead and re import from book import book when I create a new book I'm going to need to say this book is will say Harry Potter and it's by JK Rowling I have to specify both arguments to be able to create a book and if I had only provided one argument just Harry Potter well then I would have gotten a type error because in it was missing one required positional argument it's missing the author argument in other words to create a book I need to provide an author but I didn't but some languages like Java and I think other object-oriented programming languages will allow you to have different constructors where sometimes you want to be able to only provide a title and not an author and sometimes you have both a title and an author for instance and so what you can do that in Python is by giving these arguments default values we're back and say author by default it's gonna be none as in has no author and so now if I say from book import book let me say book b1 is going to be a book called Harry Potter whose author is JK Rowling and let me move it to this side since my covered up b1 has a title and b1 has an author but if I can also define a book b2 that is just Harry Potter leaving off the author argument notice no error this time because if I didn't provide a value for what author is equal to it's just going to use that default value the value of none so B twos title now is still Harry Potter but if I try and get a B twos author there is no author but you just always assumed that authors JK Rowling for every book or you could do that you could you could give it a default author particular Rowling for everything certainly if you wanted to all right I don't want to get us too to take too long so if we want we can maybe forge ahead and we'll come back to look some other questions we might have missed all right let's go ahead and keep going that in that case what I'd like to do is I would like to be able to add some code to this particular book I'd like the book to be able to do something and so what I'm going to do is I'm going to add a special method called print info and print info is going to be a function that I can use on a book that prints out information about the book remember that objects in the object oriented programming sense are a combination of data and code data is any information associated with the object and the code are going to be these methods these functions that work objects that can do something with the object and one thing I might like to do is print out information about the book so I'm going to define a function called print info that takes self again as its argument self is going to be this implicit argument that's always going to be provided whenever we're calling a method on an object and that allows me to access the properties of that object so if I want to print out the book's title I can print self dot title and then maybe you just concatenate it with was written by or I'll say is written by his present tense self dot author so all the print info function here is going to do is it's going to print out self dot title it's going to say is written by and it's going to add self dot author to the end of that and so let's go ahead and try that out I'll go ahead and reinforce the definition of the book class I'm gonna go ahead and import the new definition of what the class means create a new book Harry Potter whose author is JK Rowling and now I can access the properties individually be a title via author but I can also now call this method I can run this function on the object by saying B dot and then the name of the name of this method is called print info so I'll say B dot print info and what I get is okay Harry Potter is written by JK Rowling since we since we define that function with self you know it's part of that class when it sees B dot it basically injects B into the function and therefore we have access to all of B's information but you could have done C you could have done D you could have made however many books you want and they all are going to print their own sort of self-contained message yeah exactly so if I define another book b2 for instance would find it as another book that some will do the last lecture written by Randy Pausch who was a computer science professor at Carnegie Mellon University I can say be to print info and okay I get an entirely different title and author B still has its own print info that's accessing the properties of the B object so this is the same function the same method print info but depending what object I used to call the method the data inside of it is different and so the function can behave in different ways for example awesome somebody somebody Edie Schwartzman said that they like your web programming course no I'm glad you like it yeah and then someone's asking oh it's the same person actually that's sort of a saying if you could use three-point 7s data class for the data class I've actually that's a feature of three-point-seven that I have not yeah I haven't really explored that maybe potentially someone mentioned formatting with F strings is a new feature in Python 3.6 definitely something you can do as well I'm just using concatenation for simplicity but if you wanted to you could tack an F at the beginning of the string to say this is going to be a formatted string and then use curly braces to plug in values where I could say self title is written by self dot author for instance and that's gonna have the exact same behavior may actually be a little bit more efficient in this case saben 3:42 asked how to practice learning Python they say they know it but can't solve any problems how can they increase their problem-solving technique probably the best way is to practice solving the small problems and a few where you get one of my favorites for this they vary a little bit in difficulty is project Euler got a project Euler I'll show you some sample projects small tangent will go back to object-oriented programming in a moment basically what project Euler is is this collection of a lot of problems there are 644 problems and each of these problems are asking you a question and usually the way to answer this question is to write some code that can help you to answer it so I'll click on question one for instance it says if we list all the natural numbers below 10 that are multiples of 3 & 5 we get 3 5 6 & 9 okay those are the numbers less than 10 that are multiples of either 3 or 5 and the sum of these multiples is 23 and then the question is alright find the sum of all the multiples of 3 or 5 below a thousand and certainly you could do this by hand and figure out what the answer to this is but what's going to be easier is alright see if you can write a Python program that gets you the answer to that question and then you can plug it into the website and see if the answer is correct so all the problems resemble something like this they introduced some problem ask you a question and usually the way to solve it is going to be to write some program to be able to do it and added brownie points if you can come up with an efficient solution to the problem trying to figure out how to get it to run very quickly so good practice for Python there are many other websites that have sample coding problems as well but I found these to be at least interesting problems that often involve a bunch of different types of programs that you have to write and a bunch of different ideas have you done all 700 I have not done all 700 I've done a couple of them beautiful young gentleman asked can you avoid having to give default values using a hash or an array as a parameter using a hash or a hash table is probably what they mean using a either hash table or dictionary or an array as parameter to a function can you avoid having to give explicit default values in the case of a Python function your choices are to either give the argument the default value or when you call the function to provide a value when you call the function so we don't need a default value on author but in that case now you're going to need to tell me who the author is when I try to create a book they may also be alluding to K arcs or keyword arguments oh yes there are ways where you can specify that you're going to take just some number of optional keyword arguments that could be anything usually that's going to happen if you don't necessarily know in advance what those arguments are going to be but then you can use those arguments in particular ways you've maybe seen this in use of your taken cs50 when you are executing database commands you had DBD execute and you would say like select star from users where username equals username and we would provide this like username argument to DB execute we didn't know in advance what all of the possible arguments to the execute function were so these are just keyword arguments that could be anything and then the execute function job is to say all right let's look at those keyword arguments figure out what they are and figure out how to substitute them into the query ultimately that gets parsed as a dictionary right yeah it gets parsed as a Python dictionary you are you afforded the ability to pass in a dictionary and have that be your keyword arguments if you do star star keyword arguments can you pass in the dictionary is that parameter and it will consider the same you would have to there's some special syntax where you add an asterisk before it in order to sort of explode it out into all the various keyword arguments so it'll do we're sort of getting off-topic but this is good just talk about Python in the language so we'll go ahead and say the function takes some keyword arguments and prints out we'll just go ahead and print out the keyword arguments for now and if I call the function passing in a equals three and like B equals four for instance what I get is alright a dictionary that has a equal to three and B equal to four but if I have a dictionary already called X where a is set to three and B is set to four if I try to call F with X that doesn't quite work but I think if you do F star X that means take the dictionary and like split its components into various different parts maybe it's a star star yeah start star x sorry you say star star X meaning take the dictionary split it up into all the component parts and then we're able to take the dictionary basically pass it in as keyboard arguments I use that this the sort of this the pointer syntax very rarely and in Python yeah it's useful in certain circumstances though a little bit different in this particular case okay let me just make sure all caught up in the weekend oh we can try to steer course-correct back to the object-oriented programming but all this the sign stuff is a lot of fun I really like going into all kinds of stuff Oh Senate pro it asks what about star args which we got into and star star for unzipping yep we did all that and then remote is asking how can variables be set to private and you did we we mentioned that a little bit earlier it's a slight difference between Python and Java and that particular Suns cool and then this is a good question actually the cake 1990 saying I see object-oriented programming all over the place is this always justified when does it make sense to stick to object oriented programming compared to traditional imperative or functional programming yeah that's an excellent question and the choice of programming paradigm really depends upon the type of program that you're trying to write and there's not necessarily one right answer here oftentimes object-oriented programming is a good choice when you're trying to model real world things that often it's easy to wave you have a database where you have a bunch of objects that represent things in a database object-oriented programming is often a useful way to try and model that data someone mentioned the web programming course for instance that's now available on EDX if you look at that when we talk about dealing with databases and writing web programs that interact with databases we spend some time talking specifically about pythons direct oriented programming syntax and talking about how we can leverage the features that are given to us an object-oriented programming to be able to interact with databases more effectively and in a cleaner way imperative programming definitely has its place - certainly for most of cs50 s problem sets for example they don't necessarily line up quite well - trying to model objects in the real world but certainly you could write classes that try and solve them and so imperative programming makes sense as a style there and then functional programming which which was brought up as well as an entirely different paradigm in programming which was also very interesting and perhaps worthy of a topic another time yeah but that has to do more with the treatment of functions as values of their own where you can begin to take functions and pass them as arguments to other functions compose them and to higher-order functions that you fold over and do various operations on and there's a lot of very interesting applications of functional programming that gives you access to some nice recursive tools the ability to write a lot of programs in a very elegant way and so there's a lot there as well one big sort of thing that people could take about object-oriented programming is state for example being a thing that's very muddled if they can hard to manage for really big applications and functional programming tries to eliminate that right functional programming in general a pure function is a function that has no side effects such that no matter what input you provided to the function it's always going to provide you with the same output no matter what and so that can be an advantage there - and those are not the only paradigms of programming that exist there's also lazy programming and lazy evaluation which is a style of programming where and we try and delay computation for as long as possible until we need it it's often paired with functional programming but it allows you to do things like represent infinite data structures if I want to represent an infinite amount of data an imperative programming language could never be able to do something like that because our computer physically can't store an infinite amount of data but with lazy evaluation the lazy programming you can do that by just saying we're gonna store the infinite amount of data but we're not going to bother calculating the later pieces of data until we need it and so it offers a lot of interesting tools that you might not have thought possible from just the world of imperative programming there's declarative programming and then there's all the whole sort of like logic based programming with programming languages like data log and Prolog for instance there are a number of different styles of programming long story short of wikked object-oriented programming is just one of them that has a particular uses when we're trying to model things from the real world we have a lot of streams future streams we got to do ok cool let's get back to the object-oriented programming that was an awesome assign though all right let's go back to object-oriented programming what I'd like to do now is maybe define a new class we've got a book class and maybe I wanted to find a class that's going to use this book class maybe to find a class for I might want to use this book data somewhere maybe inside of like a library for instance where we have an inventory of books and where books can be checked out or returned for instance so let me go ahead and create a new file called library PI and I'm going to create a new class called library and I'm going to define an initializer a constructor function and this constructor function right now I'm just going to store like a list of books what a library has within it is a whole bunch of books and so we're going to say self dot books and I'm just gonna by default set it equal to the empty list when I first create a library there are no books that are inside of that library by default so we're just gonna make it an empty list again more of the theme of sort of modeling the real world with ocular programming exactly I'm defining what a library is creating a blueprint for a library where I where about whenever I create a library I'm going to initialize it with an empty set of books and now what I want to do is add some code to this library some operations that I might want to perform on this library for instance I might want to add a book to the library out a book just called book for instance and what is this add book function window do well it's just going to take self dot books we're sorry add book takes self as its first parameter that's the name of the library object and it's also going to take the book that I want to add it and I'm just gonna take the self dot books list and I'm going to append to the end of that list the new book pythons way of adding to a list if any some folks are new to Python also shout out to David is in the chat says thanks for tuning in everybody provide a vis and kind words for them yeah this is nice this ability to sort of think a long time with like what like I can also envision maybe like lookup book right you know it takes in a string for a title or an author or something like there's a whole bunch of avenues we now have yeah exactly so we can begin to some of the features that people have featured suggestions feel free to throw them into the chat I don't have any particular features we need to implement so happy to be a little bit creative here so let me go ahead and import the book class and import the library class and what I could do is I could also put this import statement at the top of the library class so I only need to do one import but now what I can say is all right let me first define a book called Harry Potter by JK Rowling we'll call that book b1 and let me also define b2 which is going to be another book will do my sister's keeper by Jody picot another excellent book so I have two books and let me know create a library so I'm going to say L is going to be equal to a new library and notice that other than self there are no other arguments to the init method inside of this library class and so I can just say L is going to be equal to library so I've created a new library and if I want to print out the books in the library I can say L dot books and I see okay in empty list of books but if I say L dot add book let me go ahead and add b1 to my library I've added the book and now if I type l dot books I see okay inside of L books is my list inside of which is this book object at and then this long number which is a little bit cryptic but long story short Python is trying to come up with some way of representing this book for instance and the best way it can come up with to represent it is where in memory the book happens to be stored and so this book happens to be located at this particular place in memory now granted that's not in a great way to represent a book maybe I would like to represent that book by its title for instance just to make it a little bit easier to look at and so one thing that I can do is I can go ahead and go back into book top pie and let me add another method to this book class let me go ahead and add a method that I'm gonna call wrapper for representation this is a special keyword in Python and if you define a wrapper method on a class that's basically going to define what it is that that object looks like if you try and display its value for insta and so here I can say let's just represent a book by its title I'm gonna return self dot title to mean if I want to represent a book let me go ahead and just represent it by its title for example let me go ahead and from library import library again I'll go ahead and define my two books oops from book in poor book let me go ahead to find my two books and let me go ahead and say l equals library and now if I say L at book b1 and print out Elle's books what I get is Harry Potter inside of it that's great much more readable than just looking at the memory address now I can see all right what books do I have inside of my library well I have one book and I just have Harry Potter inside your biggest sin though is they didn't specify a title for me I didn't specify the exact title of it will have to live with that for now if I wanted to though b1 is the name of the book Harry Potter if I set B once title equal to Harry Potter we'll go with a different one and the Goblet of Fire now b1 if Harry Potter and the Goblet of Fire and if I look at l dot books indeed it's change now Harry Potter and the Goblet of Fire is inside of the library it's nice it's very flexible in that repper wrapper function yeah so now if I I can say L dot add book b2 and go ahead and print out L books and now inside of my library of books I have two different books Harry Potter and the Goblet of Fire and also My Sister's Keeper we could even you know add on to it like Harry Potter and the Goblet of Fire then by the author just so you give it even more information but them I mean that might be a little bit much but if we really cared about that detail it's very easy to extend that functionality yeah exactly I could define yeah you could you could extend the repper function to add whatever functionality you wanted in order to get the effect let me shout out we have a bunch of people that just followed so I like ten notifications just now so let you play our 980 the Hari web Vladimir Putin CS knology frost frosty ty I think someone I'm saying that one Eddy so healthy at Crewe 22 beautiful young gentleman flying sea pig 7 342 ray 911 debunk a beggin show and Raoul Ibuki thank you all very much when they follow I got like 10 in a row while you were and there's even more so arch defender also and Randall J and they've opted for the follows appreciated they were tuning in for that object oriented programming cool also we should make sure that we didn't miss any questions here o in some so bad was saying we'd love to have you talking about functional programming if you if you ever want to come back and talk about functional programming my friend shows me is Haskell from time to time and it makes my head hurt and to your point about lazy evaluation I believe had schools the lazy Philadelphia half-closed a functional programming languages that makes very much use of lazy evaluation and if you haven't seen functional programming before it can be a little bit tricky to wrap your mind around at first but once you start to get the hang of it it's very powerful and allows for a lot of reasoning about programs in a very elegant way and I mean pythons generators are even there they're technically lazily evaluated if they like you can call range of like some crazy answer and it won't evaluate it instantly yeah that's true in Python 3 at least the range keyword takes advantage of lazy evaluation and some some thumbs to be able to do that em cotton Bert was saying we can make a check at a book the library yeah in fact I think that's what we'll do in just a moment yeah sure how would you go about saving books objects says Senate Pro how would you go about saving book objects in a database would you add some method to do that oh ok so if you wanted to save it in a database you would have to basically first have a database on hand to be able to access and then usually what you'd use is what's called an ORM an object relational mapper and what that's going to do is let you treat rows in a database as you would treat objects in an object-oriented programming language like Python the one that I use in Python is called sequel alchemy and if you take a look at the web programming course like Colton posted a link to in the chat and then we have beyond beyond on the YouTube writing that's public right uh it's cs50 but yeah I think it is public yeah so we could plug that is because you have a lecture on ORM api's yeah there is the web programming one is a little more in-depth but there's certainly one from seats so in January there was a class we offered called cs50 beyond there was also a lecture in there that was also about using object-oriented programming with ORM Zand api's as well so you can take a look at that yeah that link I just posted the chapters for Bryan's beyond course so I knew a new course that Brian taught this brings awesome course so yeah so I guess in that sense it would be kind of up to whatever database they want whatever ORM they want it wouldn't be there's not one true way to do it yeah not necessarily just one sequel alchemy is a popular one so that's definitely when to look into if you're using Python and if you're using a sequel database but there are other options that's what we use for cs50 or and seek welcoming right for some of our tools yeah so like help 50 for instance has some object-oriented programming it and that's all sequel alchemy the what I mean is the like db2 execute oh yes yes underneath the hood that's DP that execute is really using sequel alchemy in order to interact with the database that's correct KooKoo oh no one doesn't say as he was saying we could make it so that it reads the books first sentence I guess if we wanted to store the whole textual data of the book if we wanted to store the text of the book we could definitely do that well do that live on stream we'll just right out of the hole yeah there's an interesting question of this is an entirely separate issue but I study computational linguistics and so there's an interesting question of how to get the first sentence of a book you might imagine that if you have the text of a book and the text of the book is like this is a sentence this is another one like an easy way to think that you might do it is just say alright let's split the text on like periods and like whatever there's a period we can say there are sentences and and we get okay this is a sentence of the first sentence but that's not always the case right because sentences might end with an exclamation point so if you split it on periods well alright now this is more than one sentence which isn't quite right and even if he said or I will periods and exclamation points and question marks are all boundaries for sentences you run into other issues too because if you said like mr. Jones walked to the store and now you tried to split it on periods well now the code things that Mister is a sentence and so there's an interesting computational problem of how to even take text and split it up into finances but that's a computational linguistic issue is there in a nutshell is it typically like would you would you kind of bucket eyes like nouns verbs prepositions adjectives and then use some sort of grammar applied to the text to figure out what like what constitutes a legal sentence and then use that heuristic you can although that doing that is not totally precise because it's not always clear to the computer how exactly each part of each word functions of a sentence our taggers that are quite good at that but that becomes a more interesting computational linguistic problem I know DK is a Python library that deals with natural language a lot one potentially worth looking into that's something of interest any of you but long story short there are ways of solving this problem that are pretty good but it's not quite as simple as you might think it is I imagine yeah I imagine you can't apply a strict grammar like you could to C for example to natural language because people use it in flexible ways right and there's also situations where they're potentially words that the programmer who wrote the parser doesn't necessarily know so if I have a sentence like I saw two wags you as the human can probably discern that a is a noun but a computer has never seen the word walk before it doesn't have a dictionary that can just look up the word bug and say okay what is a noun we recognize it here but that becomes a little bit of a trickier issue yeah that's interesting you'd have to like you infer from context of the sentence right yeah and that's not an easy thing to solve a lot of cool asides today I apologize that we were taking a little bit of time away from the object-oriented know aw really people are saying thank you so thank you phone brands helps me keep my skills up to date says Vanette ah kifo is asking hello just saw you from your Jas core so they were tuning into your web course jump jump one two three maybe do something like book in Lib equals a dictionary and it will store the books number in stock in the library oh so mapping mapping I guess maybe titles to numbers for the stock of the book I guess that would be something yeah so actually this is sort of actually will probably stop going we can get back to object-oriented programming this is sort of what I wanted to talk about that when we're dealing with books in a library there's some additional information about books that we might want to keep track of we might want to keep track of the inventory for instance we might want to keep track of who has checked out the books for instance and so you could imagine I could take this book and say alright let me go ahead and add to the book class let me go ahead and add an inventory and maybe inventory starts off as one or whatever and you could add borrowers to keep track of whose borrowed a book but this isn't quite ideal because now I'm adding to the book class information that doesn't pertain to all books it only pertains to the library but this is like a books like this is like a book stock idea not a book concrete book yeah I mean you could associate the data with the book but you can imagine that then we'd no longer be able to use this book class for other things if I wanted to use the book in this class in a program that we're used by some book archive website for instance it doesn't have the inventory of checking things out but just keeps track of titles and authors for instance or like keeps track of book reviews for instance where the book review website doesn't need to keep track of the inventory of each book they don't have inventory yeah we'd like them to be able to still use the book class but we want to be able to sort of create a special version of the book class specifically for library books and so what we're gonna get I know is the idea of inheritance in object-oriented programming the idea that I can say let me go ahead and create a new class but specifically for library books so I'm gonna create a class called library book and you could imagine that a library book has a lot of the same things that a book does it has a title and as an author you don't have a way to print info and so I could copy all this code and paste it into library book pie but that's probably not a great way to start doing things as soon as you start copy pasting code you should always be thinking to yourself like is there a better way to design this code in order to achieve what we're trying to achieve and so what I'm gonna say here is I'm going to make library book what's called a subclass of book in other words the library book is a type of book that's going to have all the features that a book had but it's gonna have some additional features that are specific to library books and so I'm going to in parentheses say book and what this syntax means is that a library book is going to be just like a book but now we're gonna define some additional features for the book and so let me just go ahead and say pass right here just to say don't do anything else for now I'm gonna have to import book here no the nice thing about modern text editor is is that live sort of real-time yeah the underlining is tell me what I'm doing wrong so now that I've created a library book that is a subclass of book right now I can treat library book exactly the same way that I treated book I can say from library book import library book and now I can say all right let B be a library book named Harry Potter and this author is JK Rowling for instance and a B as a title B has an author I can say B dot print info that says Harry Potter is written by JK Rowling all the same things I could do with a book I can do with a library book in the exact same way because it's a subclass of a book it's baby it is a book but it now is going to let me add library book specific features to it nice because also you know what if somebody changes the book class right right if you had just copied and pasted it your version would be out of date with the other version exactly yeah so what I can do now is let me go ahead and create a new constructor for a library book and when I create a library book I want to do a couple of things I'm going to have a title and I wanted to have an author but when I create a library book I also want you know inventory I want to know how many of this book do I have in stock in the library for example and so when I do that what do I want to do well what I want to do is I want to first do all the stuff that the books init function did remember here in book pi its init function took care of setting up the title and the author for me so I want to do that stuff and then I also want to set the inventory variable so let me do the inventory part first that's the part you seen before self dot inventory equals inventory and now I could set the title of an author by saying self dot ID equals title self dot author equals author but doing that again is gonna feel like I'm repeating some code I've got these two lines of code here setting self the title and self dot author then same as these two lines of code in the book class and so here we're introduced a little bit more terminology if library book is what I've been calling the subclass of the book class in other words a library book is a type of book that book is going to be the superclass of library book book is going to be the class that's considered like the parent class the book that I'm inheriting from and so if I want to call a method of the superclass I can use a special Python keyword called super super it gonna mean run some code from the superclass and in particular let me run supers init function passing in title and author so a little bit cryptic but what I'm saying here is when I initialize when I construct a new library book let me take the superclass the book use it's init method to say let's give this book a title and let's give this book an author and then let me go ahead and say alright let me set the inventory because that's not something the book did that's something on what the library book to do in this case and the reason we have to explicitly call line six is because we're overriding the init function in the library book class exact so it doesn't it won't run the old books in it it basically sort of replaces it or paints over it with its own version so we need to get that functionality we need to explicitly do that great so now I've created a new library book and maybe I also want to define some functions so maybe I want to say let me define a function called check out that it's going to check out a book and we need a name like who is the person that's checking out the book and so okay then we're gonna go ahead and say but I guess we should probably add something like self dot borrowers like who are the people that have borrowed this book which is just gonna start off being an empty list and now inside of check out what I can say is alright let me say self dot inventory minus equals one in other words take the inventory decrease it by one and let me go and say self dot borrowers dot append name so what I've done here is that basically said when I check out a book let me go ahead and decrease the inventory and add the person's name whoever checked out the book to this list of borrowers to the list of the people that have borrowed the book and to relate it to that to line eleven actually someone asking funny bill Mac was asking is there any way to protect a class variable for example I have an age variable in an it and when the user basically enters a negative number how do I handle that and I could see that happening even here to on on eleven we're not really doing any checking for yes so I was gonna get to check me along but we can we can try to do it now for this simple case we can just add checks we can say you know if self dot inventory is less than one meaning if there's fewer than one books in the inventory then let me just go ahead and print an error message say like sorry not available you know in practice I probably wouldn't want to do something like this I would probably want to define an exception an error in Python and say like raise no more inventory error like to find some exception class it would be the error that gets raised when there's no inventory but for now I'll just go ahead and print sorry not available for this book and then just return to say exit this method and so here we're adding that check if you want to add checks when you set like the attribute of an object you can use some special methods called set adder and get adder for setting attribute and getting an attribute we're not going to go into too much detail about that here but something you can take a look at if you would like to that exception thing you mentioned we could do that also in the constructor to what if I be do Mac was asking and raise the same kind of exception age not a valid exception or right right right so all right let's go ahead and give this a shot I'm gonna go ahead and say from library book import library book and let me go ahead and create a new book that is a library book Harry Potter by JK Rowling has been the example we've been using oh okay great give me air I only gave it the title in the author but a library book it's in it constructor takes an additional argument it takes an inventory argument so it's not enough just to provide a title and an author anymore I know also need to say you know there's two of these books in stock right now so I can say let's look at the title let's look at the author let's look at the inventory I can access all this properties I can print info about the book and it's gonna call the print info function but let me go ahead and call the check-out function and let's say Colton is going to check out this book let me see my Harry Potter alright and so now if I check beyond inventory inventory is one and in fact if I check out beat up our Wars and now it shows me that our Colton if someone who is borrowed this book I'm like if I might like it so much that I'll check it out again you could check it out again if Colton checks out the book for a second time B's inventory alright it's nonzero and borrowers we see Colton there twice Colton has checked out the book twice and now if I want to come along and try and check out the book alright sorry not available we get that error message because now our inventory is zero and so that check was able to come in and deal with that we get a lot of nice readability here we you know rather than having to maintain a bunch of variables and data structures kind of an ad-hoc style we can literally think in terms of how we would think about this in the real world you always say Oh check out this book you know manipulate the library you know how we have library books we have books we have all these different you know rule of context it's really nice yeah it offers a very nice way of mapping on real world concepts to programming and that's really what object-oriented programming is designed to allow you to do effectively Newman 118 is asking how much did I miss we're giving well I'd say we're about an hour crop we have another 30 minutes or so but a the video will get put on to YouTube and you can watch the twitch bot afterwards so definitely catch up but where I think approaching the tail end are the cs50 lectures on Twitch a separate series they are David kindly plug them he's saying comp linguistics sounds like an interesting field I mention you must like it because you're crying yeah I do a lot of research and computational linguistics as part of my undergraduate degree so I spent a lot of time looking at problems like the ones we were looking at a little bit ago that's cool I di I don't know if I've thought about that specific way I've thought about you know language part processing and parsing but you brought up a good example Adam said just up did you finish the breakout assignment for the game - of course that was hard but very rewarding excellent job definitely keep us up to date tomorrow yes yes oh did we not have okay Ellen won thank you for bringing up the fact that we're not using the programming tag I didn't see the programming tag but I'll definitely check on that yeah who's saying hello from Germany thanks for thanks for tuning in from Germany oh guy why has an interesting question you probably mentioned this at the start of the talk how does Opie build on top of the knowledge we learn in cs50 they want to take the gaming course yeah so if you've taken cs50 you were introduced to Python as a programming language and object-oriented programming is just a slightly different programming paradigm that we don't really spend a whole lot of time on in cs50 and this programming paradigm is designed to allow you to think about your code in a slightly different way in particular it's useful for thinking about your code when you want your code to be able to model things in the real world in this case we're modeling books as you might find in a library for instance and trying to figure out what data is associated with those books and what code is associated with them so it's a programming paradigm a slightly different way of thinking about writing and organizing your code okay does the repper function also work for a library book if I didn't implement one in a library book oh yeah sure if I just type B right now it says Harry Potter it's giving me the title of the book and that's because the wrapper function is inherited from the book class if at any time I have a method that isn't defined in the subclass inside of library book what's immediately going to happen is Python is going to look to the superclass it's going to look to book to try to figure out all right which way is there a wrapper function in the book class and if there is well great then we can just use shut to nca a gif who's fat he'll domak an average l1 Hilario parabolic and Tim fbfbfb thank you all very much for the follows let me just make sure we're all caught up here 7/3 42 is asking we're designing a model or properties for a class do you need to plan ahead when you when doing that in general yeah in general anytime you're designing a class I always like to recommend planning out the code you're gonna write thinking about what the different parts of it are so you can figure out how best to organize it because if you just dive right in you might be able to make some progress but you might hit a point where you realize you know wait a minute there was a different design that would have made some of this a little bit easier so thinking through how you're approaching the problem and how you're designing the problem before you actually try and approach it and actually write the code for it it's often helpful cool is it possible to inherit to other classes like class library book where it takes a and a B where a and B are two different classes yes you can so you can have if I define a class called a that defines a function called foo that prints hello and I define a class called be the defined the function called bar I'm sorry I'm gonna have to say plus a define foo self and print hello and to find a cloth be the defines bar that prints goodbye I can define a class C that inherits from both a and B and I'm just gonna say pass to say there's no content inside of this class and so if I create an object that is of type C then I can call foo and I can call bar because it's inherited from both Class A and it's inherited from Class B so we get access to all of the code and all of the properties that were present in both of those parent classes if so pipe this is something we call multiple inheritance not every programming language supports that the Python does where the idea is that you can have a class that inherits and gains properties and data and methods from more than just one class yeah I see this I've seen it a couple times I know that it's a lot of people frown upon it and that's why a lot of languages don't support it but I feel like I have definitely seen legitimate use case it's been a while it's been a while since I've seen that yeah yeah so it adds some it makes things a little bit more complicated it makes sense a little bit tricky to reason about you can imagine like if I had a Class A that defined foo that prints hello and I have a Class B that defines foo and prints goodbye and I define a Class C that inherits from both a and B well when I create an object of Class C what should foo print it inherited from both a and B they're both the parent class but they define different foo methods one that says hello and one that says goodbye so when I call object a foo which one should happen it becomes a little bit tricky in this case it's probably gonna go with hello I think yeah it's gonna go with hello but it gets complicated if the a and B themselves have parent classes that might be different things I can interact in different ways so Python actually has a fairly complex algorithm for trying to resolve which class should do what it's an algorithm called c3 linearization we're not gonna go into detail about it because it's probably beyond the scope of connections for Stanford this so this is interesting yeah so c3 linearization is an algorithm that's used to obtain the order in which methods should be inherited so if you have multiple inheritance going on a bunch of different classes inheriting from other classes what you get is the method resolution order which is the order of which methods should be called when you try and call a function yeah the Wikipedia page goes through some examples we're not gonna dive into the details of the algorithm right now it's a little bit complicated but know that there is an algorithm for trying to figure out which code ultimately and you can avoid it by not using multiple in here you can avoid it by not using multiple inheritance oh I'm sure there's some pretty good use cases for it God's of 119 with the controversial every olp implemented in a non java language is a waste of time I don't know if I find myself in agreement with that that sounds a little bit like it sounds a little every language has its own advantages and disadvantages what's the best way to test methods in Python particularly working with larger code bases yet so test-driven development is important part of development testing code to make sure that the code does in fact work in Python the library that I like to recommend is a library called unit test unit test I thought it's a unit testing framework built into Python and you can take a look at the documentation here and basically it offers a whole bunch of methods for being able to quickly and effectively test your code in order to define test cases things you want to test about your code to make sure it works and then easily run a whole suite of tests against your code to verify that it works as well check 50 the tool you may have used in cs50 that does some automated correctness testing in your code is really using unit tests behind the scenes to make sure that everything is working and the nice thing is it comes with Python it's just part of the standard library yeah yeah definitely very useful part of the Python standard library just make sure you miss anything here Elmen zesting are they grad students or TAS so you're alright you're ahead teaching what's the what's your career role and I was the head Teaching Fellow last year for last semester for cs50 yeah okay and Bryan you're currently Brent's currently an undergrad and then I am a just a full-time technologist not a not currently a student at the University cool all right let's let's continue alright let's go ahead and keep going alright so other features of object-oriented programming that are worth noting right now if I have a library book and I probably shouldn't match probably should have kept it up but import library book and let me go in say a B equals library book I'll just go in and say title author well we'll give it an actual title we'll say Harry Potter JK Rowling and to an inventory if I say B dot print info right now it says Harry Potter is written by JK Rowling which is fine because the print info function was defined by the book class and the information that we printed out about a book was the book's title and the book's author but you might imagine that if I want to print info about a library book I probably care more about more than just who wrote it I probably care about what the inventory is I probably care about who's borrowed the book for instance and so those are all things that I might reasonably want information about at this point were practically approaching like rendering a table yeah almost you could imagine doing that certainly so what I'm gonna do here is I'm going to override a method of the book class right the book class had this print info method that I've been using but I'm going to override it by defining my own print info class inside of library book now before when there was no print info class inside of library book if I tried to take a library book and print info about it you would just go to the books class definition of print info and use that code but now that I'm defining a print info class inside of library book I've overridden this functionality so that when I try to print information out about a library book I'll get this particular behavior and so I might start by saying all right let me just print things out in a nicer format let me say title of the book is self title and let me go ahead and say the author of the book is soft author and let's say inventory remaining is self dot inventory and then let me go ahead and say borrow where is it and I would like to have like self borrowers here this is gonna print out a list what I'm actually gonna do is join this list together so python has some special functions for being able to do things like this where in Python I can say sum if I have a list of names where names is equal to let's say Colton and Bryan and David for example I can say let's take the comma and join these names and I get Colton Brian David Colton comma Brian comma David for and actually make it a little bit nicer I'll go ahead and separate it with a space after the comma and so it shows up as name separated by a comma so I take a string and I can join together a list by placing the comma in between each of the elements inside the list and so I'm gonna do the same thing here and brain instead of self dot borrowers I'm gonna take comma and join self dot borrowers to say take all the people who have borrowed the book and just put them together with a comma in between each of them very pythonic a way of approaching the problem yeah exactly and so we'll go ahead and import library book we'll go ahead and define this book again and now if I say let's let Colton check out this book if I say book print info and see what that looks like we get okay title is Harry Potter author JK Rowling one inventory remaining and borrowers just Colton if I now check out the book then print info all right zero inventory remaining and now I get new information about who has in fact borrowed the book nice very solid people were very happy about that unit test library that you mentioned ray jam Prince Arthur and kamdev thank you very much for the follows pull to ask an interesting question could you create classes for non nouns could you create classes for not nuns well I'm sorry sure you can create a class for anything a class is just going to be some type of thing that you were going to create but usually the class is going to be a noun because what it represents is usually some entity that you're trying to represent in your program and generally that entity is going to be a noun for instance if it's a verb some action usually that's gonna be a function or a method inside of one of those classes some operation you're going to be performing on the code and I don't know what other parts of speech you come up with adjectives probably most resemble like the properties of the object there you could say maybe the book has a color and you could set self dot color equal to the color of the book for instance and those information about the noun are generally stored as properties within the object and so this tends to be part of that paradigm cool makes sense why not use the terminal reading vs could run Python it's super useful as adamantine 500 you certainly could I've used it before I personally just for happened to really like I term is the terminal program that I use on Mac so I'll generally use that and when I use vim which is the main text editor that I use most of the time I just do everything from the terminal and so I never end up in vs code also nice to have a full screen like this yeah okay cool cool me just make sure we didn't miss anything how would you override a method that was declared in the superclass that's exactly what we did actually so in the case of library book book is in fact the superclass print info was the method that was defined inside of book and inside of library book we overrode the method of the superclass we defined a new print info function which was going to basically override the behavior of the book class's print info method and say you know if it's a library book here's how I want to print information out about that book all right I think we're all caught up on questions if you have more oval P stuff okay I guess the last thing we could do is maybe add to this library class right now we have add book maybe we want to allow the library to let someone check out a book for instance so let me add a function to the library called check out and if I'm checking out a book maybe I'll specify the title of the book and the name of the person who's checking out the book obviously in the real world you'd have to account for the possibility that multiple books might have the same title here we're just gonna make the assumption for now that all the titles are in fact unique and so here will be the code we'll go ahead and say for every book in self dot books if the book's title is equal to the title that was passed in then let's go ahead and check out the book and how do we check out the book when we say book check out passing in the name of the person who's checking out the book and then go we'll go ahead and return meaning exit the function at that point so let's look at the logic again for every book inside of this list of books we say all right if the title of the book is equal to the title of the book that we want to check out then go ahead and take that book and check it out who's checking it out the person's name here we're calling the check out function of the library book and then we're saying returned and if we get to the end of the for loop and we weren't able to check out the book because there was nothing with that title let me just print book not found just to give some sort of error message at least for now nice it must be a pretty smile if I'm definitely if I'm the one borrowing it's just gonna be a small library for a book in self that Fox yeah so certainly this is we can spend an entire stream talking about algorithm design this right here is what we might call a linear time algorithm to try to find a book to check out where I'm going through the books one by one checking each book is this the book I want to check out it's not the book I want to check out in practice probably not the way that I actually want to check out a book if you think about things in terms of cs50 s first lecture if you recall the same method that David used to try and find a name in a phonebook for instance we were able to say you know there's a linear time algorithm of looking one page at a time but there's also a log n time algorithm of saying you know let's sort them keep the books in sorted order and go to the left half of the right half of this list depending on the title of the book that's certainly something that you could do as well in order to get this effect I had a brain fart I actually thought this function was checking out all the books in the library like iterating over all the misread the code yeah check out functions just checking out one book but it is a good point that it is iterating over all of the potential books and so in practice if I had a book of a library of millions of books I probably wouldn't want to be using a function that looks something like this because it ultimately just begin efficient yeah and you simply use an index data structure dictionary or something creaking index I access it by key right so if you have some sort of hash table where you can access by a string key then you can get even more efficient lookups in that sense as well cool cool I'm LM one ask and I think this might have been in reference to the F string that you said before but it asked me basically if that was the new print format standard and how does it compare to a string dot format yeah so the F string you can basically use wherever you could have used the string dot format in the past it's a new feature I think it was introduced in Python 3.6 and so it's just an added way of being able to format strings in particular ways it's very similar to the modern way in JavaScript that you do the same thing where you do is back to where if you have a variable like X is equal to 28 I could say no I didn't mean to put the brackets that are called x equals 28 I could use back ticks to say X is equal to X to say plug in the value X there that's the JavaScript way of doing it it's very similar in Python you just use an F instead of the backticks so many languages are beginning to adopt format strings of that form yeah the format it seemed to me like the F string was just basically a wrapper around the format function but when you like looking at for example how to the the format specifier for printing out you know variable number of digits for example I used the same it looked like it used the same parsing or the same sort of format for that string whether use the F string or dot for the format function so it seemed like they kind of just wrap the dot format with F just to make it low syntactic sugar when would you recommend using an LP based system instead of say a state machine that asks honey-lemon blargh yeah so the type of programming paradigm to use is always going to depend upon the type of problem they are gonna try to solve and so there's no sort of one rule for trying to answer that question what I've been telling people so far today has been if you were trying to model real-world things inside of your program it's worth at least considering object-oriented programming as an option there because oftentimes this ability to subclass the ability to create instances of objects that have data associated with them are often useful operations to have when you're working with modeling real-world data so whenever you're dealing with databases for instance thinking about object-oriented programming is an option is often a good choice there but it is going to vary on the problem and it's not necessarily the case that every time you're dealing with real-world thing is that object-oriented programming isn't necessarily the way to go it just happens to be one of a number of options I would even say - you could mix and match object-oriented programming in state machines depending on what you're doing because we've done that on stream before with the games one so go watch some of the prior game I figure out the last game we did offhand was I think minesweeper we used state we mix and match we know we had state machines in the context of an object-oriented you know code base so you can definitely mix and match those depending on what you're trying to achieve kind of off topic just wondering is it necessary to learn how to use vim or just other text editors or or are just using other text editors okay asks a jump jump one tooth totally okay to use whatever text editor suits your preferences there are plenty of people that do all their editing in a text editor like vs code or atom or sublime or any number of others I happen to like vim because there are a lot of once you get the hang of it there are a lot of nice shortcuts that are useful to be able to do I take advantage of a lot of macros for instance of being able to move things around quickly and being able to copy lines so there's a brief little show of what them is like if I have a line I want it to copy for instance there are very easy ways of saying you know copy this line and paste it five times I get five copies of that same line if I have things I want to move around like one five four two three and I want to reorder these it's very easy either just like sort things put them inside of some sort of order very quickly and so if it has a lot of nice macros that that I personally like to use but certainly any text editor that works for your preferences is totally fine Prince Arthur thank you very much for the host appreciate it ordinary 713 37 and T 5e or tezi thank you very much for the follows and now I'm guessing we've reached the end of the Opie yeah we've reached the end of sort of what I had to show you there's certainly a lot more to object-oriented programming if you'd like to take this code and sort of build upon it I'd encourage you to think about all right try and implement a return feature for when you're done with the book and you want to return it back to the library how would you go about implementing that and feel free to add your own features there too there's a lot more to object-oriented programming but those are the fundamentals at least cool awesome well it was awesome let's say let's stick around for a few minutes just get certain last questions and then we'll bid adieu oh wo visas Prince Arthur does Python have anything like interfaces in Java asks adamantine bipartite I never really found those particularly useful also what about abstract classes Python in general for doing those sorts of things you'll use things like multiple inheritance to be able to inherit from the class you want to inherit from and also inherit the the sort of interface like class that you wanted to have which is an option but it doesn't strictly have the same feature as the Java has in that sense Python tends to be a little bit more relaxed about the permissioning of things and keeping things separate in that sense so it does vary a little bit Allen was asking what the difference is between print after test string and print s print string dot format oh I know in that case they they're not printing even the same string so in that case you would want to do print test string dot format right because stir it up format without an argument is that actually just nothing at all do you remember do you know a fan yeah I think they're just generalizing as to what format it's about but yeah you can you can achieve the same thing in both ways so if I have a variable X which is set to a number I can print out the format string X is X that way or I can say X is and format it with X and that's going to give me the same result those two are basically the same thing starting from Python 3.6 you can use either one and generally in cs50 we've tended to use the former just because it was a little bit more succinct cool if strings are the new standard basically says Martin yeah it seems like they definitely are short answer it's not necessary when Pam says NaCl Eric there are different ways of formatting says puppet 44:11 of n let's Protagoras saying it there are so many controversial comments but I don't remember the last controversial comment that I read besides the Java one came yeah n log n is definitely not equivalent to log N squared those are gonna be different running times so certainly there are running times that are equivalent to each other though computational complexity also a topic for another time yeah maybe we can do a future stream on that too yeah people are saying definitely not Martian Mars boy can't see people are just elaborating on the lot o of n log and comm know that if it's n to the N assuming the N is on the inside of the logarithm yeah that's equivalent to n log n because that's just the definition of the exponent you can pull the exponent down so those those are equivalent boy wait school noise in the corner the reason actually is so that if it gets truncated on Facebook which of sometimes does the person hosting the stream is still shown in the shot because isn't matter I'm in every video it doesn't matter if I'm in the shot we'd rather have the person on the actually hosting it kudos Brian for the cs50 W course Stephan one of the most complete courses out there for anyone looking to enter the web dev jungle is the next iteration out in July asks hitman 118 so we're the iteration of the web development course is staying the same for now that we did do a similar course in January called cs50 beyond you can think of this kind of an iteration on the web development course they teach us some of the same concepts but also some different ones I teach in particular teachers react which is a Facebook develop JavaScript library for designing interactive user interfaces and so we spent some time talking about that as well and so cs50 Beyond is the course you should take a look at if you're interested in web development in you've already taken a look at the resources from the web development class Mavic was asking if you can push the code to github oh yeah actually I can I can push this code to github so that you can access it if you do they just you can toss me the link to an alternate description as he was asking if you can do a stream on complan with six at some point yet potentially about something that people are interested in it's a very diverse fields there's a lot inside of it so a lot to explore try to get Athena to doing it she didn't want to do that they should have a vim stream says Lince can you implement threads and Python asks player x5x yes you can definitely implement threat to the Python you there multi-threading libraries and Python that help to allow you to do things like that isn't it called literally thread imports or is it threading through ending your might be threading yeah I remember and they have multi-threading as well and multi processing or is it just multi processing and not multi thread not I don't remember offhand can you give a brief explanation of opie and languages that don't have classes like going and Cephas NaCl Eric in short not all languages support object-oriented programming so for instance C doesn't have a class syntax like this though you can often do the same types of things that you could do in an object-oriented programming language using an imperative language like C the syntax just ends up being different Jason G says hello hello Jason good to have you with us they don't have a vim stream yeah maybe in the future we'll see who's who wants to do that thanks Heather says only caught the end of the stream but it was enjoyable hope to catch the next one I like the Panda emoji evolved golly watching from school bihari says goodbye everyone diamante is asking maybe you can do strim about computational algorithms we need a checklist at this point is it good brainy there's so much algorithms is far more than just one straight you you you can spend years just talking about algorithms and then looking at the algorithms that are out there so is oob used in systems dev asks adamantine I'm sure there are applications and systems development yeah object-oriented programming has seen quite frequently across wide varieties of different types of development stefank hello guys can you tell me your opinion on C++ as a first language it's their costs and benefits trade-offs to any language in cs50 s case we'd like to start people with C as their first programming language it's a bit of a smaller language than C++ so it has fewer language features so it's a little bit easier to get a sense for what's out there and once you've learned C learning C++ is a fairly straightforward extension on top of C it adds things like object-oriented programming for instance on top of C yeah I agree I think it's easy to get caught in the weeds with C++ C++ is probably one of the more most feature-rich Swiss Army knife languages that I know of Elmo and says go C and then o stephanas elaborating and saying as the first object-oriented programming language oh sure certainly the ideas of object-oriented programming you're really the same across almost all languages at least for the most part the idea of inheritance the idea of having objects that store data and methods the idea of overriding methods they differ in some ways some languages allow multiple inheritance but don't we just don't languages that do will differ in the way that they would algorithm they use for instance Python 3 uses the C 3 linearization algorithm that I mentioned Python - actually I think uses a different algorithm I think address use is a simpler algorithm called depth-first search I could be wrong about that though but different languages will choose slightly different ways of that sort of thing and so the fundamental ideas are the same and certainly C++ will give you an introduction to those ideas as well awesome cool cool and then one of the last things we'll Radel a couple last single read evolved Godley was saying getting associates degree in CS as an 18 year old that's awesome thanks for tuning in hope where you're able to glean some information from these shapes the hari's asking can we have a stream about Linux kernel programming have you done systems or oh sorry or rather OS yeah OS course I have not taken operating systems I've done some systems programming and I take assistant programming class Korea might be good for them are you considering taking operating systems probably not okay I know it's a huge it's a huge workload what do you see is the future of object-oriented programming will it continue to be popular for the foreseeable future I think certainly I think a lot of the libraries that are popular now that people are using especially now that JavaScript in its latest versions which is one of the fastest growing programming languages has begun to develop a lot of support for object-oriented programming with its new class syntax so that it's not just prototype based objects as previous versions of JavaScript work there's a lot of potential for object-oriented programming in JavaScript if you've seen any of my videos on reactor familiar with react you know the react is entirely based on this idea of defining classes that are components that you can insert into a webpage and react is one of the most popular internet technologies out there right now so definitely a lot of object-oriented programming happening now and in the foreseeable future just a phone saying thanks for the best and Kloppenburg thanks Brenda : crates stream thanks barn appreciate having you on Randall Jay says longtime listener first-time caller thanks for keeping today's info concise quick and clear and enjoy site topics but and get lost if you go to too deep into the rabbit hole I always enjoy Brian's teaching format so yeah sorry about all the various different topics we did get onto a bunch of tangents today hopefully some of them were interesting definitely don't worry if you didn't quite understand like all the details of the linearization algorithm or some of the stuff about computational linguistics and sentence boundary detection that I was talking about those are more just if you happen to be curious about those sort of things wanted to show you that in case I think I am any others are eager for the comp linguistics course or a session and you think python is going to be the new norm for programming and become more popular than Java as to evolve Godley it's difficult to predict these sorts of trends certainly Python is popular and continues to become more popular there's pretty widely used but certainly anything could happen is potentially the case that five years from now that'll be a whole new language that's quite popular that we're not even familiar with yet at the moment so certainly possible one language that I do have my eye on is typescript which is a strongly typed version of JavaScript which i think is a very interesting and very promising language so also one that I think has a lot of potential for the future heard good things about typescript they should look into it as well adam is asking brian is react covered in the web programming course react is not covered in the edx web programming course that one covers specifically web programming in Python so languages like our frameworks like flask and Django but cs50 beyond which is the January iteration of the similar class does cover react and teaches that as well so there are at least two or three lectures about react they're cool Igor saying bye thanks Brendon : for the stream yeah of course thanks for tuning in goodbye everyone to C's 50 and Beyond says Nieman 1:18 like that as he's saying thanks for the stream Brian you're a very good teacher no thank you David and Brian both have the same stout teaching says bihari web cool awesome well I think that pretty much wraps it up so thank you so much for coming yeah of course thanks for inviting me I'm very much looking forward to your next your next session on here let us know if you have any ideas beyond what we talked about today when it would mean today alone we probably sketched out what could be twenty more potential streams so there is always a you know an incessant influx but those awesome great ideas tune in tomorrow for a CSS stream so that'll be just made tomorrow we're talk about CSS nothing scheduled for Thursday and Friday but starting next week I think we might have a full schedule so stay tuned for you know we're still getting a lot of the dates finalized and we even have a code review session which you will be joining us for next we s yes and Susan which that'll be awesome so to keep turning in your work to us at the bitly slash cs50 twitch code review don't forget to add some of your public source code there that we can take a look at on stream if you want to get some feedback in real time from me Brian and David but that'll be it for object-oriented programming thanks so much again this was cs50 on twitch and I'll see everybody tomorrow for some web stuff so enjoy the rest of your day thanks everyone
Info
Channel: CS50
Views: 23,780
Rating: 4.965157 out of 5
Keywords: cs50, harvard, computer, science, david, j., malan, colton, ogden, brian, yu, live, stream, chat, twitch, object, oriented, programming, coding, python, oop, class, polymorphism, inheritance, java, interface, blueprint
Id: ECMSnU9ilbQ
Channel Id: undefined
Length: 94min 52sec (5692 seconds)
Published: Tue Feb 05 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.