ObjectivesDefining a basic classConstructorsAdding instance attributes and methodsAdding class (static) attributes and methodsDefining a public interfaceExecuting modules as scripts2CS 172 - Drexel University4/17/2020
Should I use OOP?How do we determine if we should use OOP?Here some ideas and questions to ask yourself:Do we want to carry around groups of variables?Might we want to have several groups of the same types of variables?Conceptually does this group of variables represent/describe something?3CS 172 - Drexel University4/17/2020
Should I use OOP?If we identify that creating a class could be useful, then the next step is to design it.This design cycle is usually:Identify the set of useful attributes and their default values.Identify what you want your constructor to doIdentify useful methodsMore likely than not you’ll end up adding attributes and methods as you go.4CS 172 - Drexel University4/17/2020
Creating a ClassTo define a class called use the following syntax: classClassName():#some more code here, indented#parenthesis are optional (for now)Good style suggests to use the camel case style for the class name:The first letter of each word is capitalized.All the rules for identifier names still apply:Letters (a –z), digits, underscoresNo special charactersDo not begin with a digit5CS 172 - Drexel University4/17/2020
Creating a Class - ExampleLets define a very basic class called MyFirstClass:class MyFirstClass():passNote: passis a Python keyword indicating no further work is to be done in this blockSo we created a class that does not do anything6CS 172 - Drexel University4/17/2020
Creating a Class - ExampleBut wait, where should we put this code?If we suspect we’ll only use it for this application, we can actually have it in the same file as our main scriptHowever, often the purpose of defining classes is to create re-usable objectSo it may make more sense to put it in its own file and import it.7CS 172 - Drexel University4/17/2020
Instantiating a ClassNow we can use our class!Assuming the MyFirstClassdefinition was put within the file lecture2.pyfrom lecture2 import MyFirstClassa = MyFirstClass()b = MyFirstClass()print(a)print(b)Here is the output:>>> %Run myFirstClassTest.py<lecture2.MyFirstClass object at 0x1021f9e48><lecture2.MyFirstClass object at 0x1021f9ef0>4/17/2020CS 172 - Drexel University8
Instantiating a ClassWhat’s up with the weird numbers/letters?<lecture2.MyFirstClass object at 0x1021f9e48><lecture2.MyFirstClass object at 0x1021f9ef0>Well, aand bare just objects, so what does it mean to print out an entire object?