100%(1)1 out of 1 people found this document helpful
This preview shows page 1 - 10 out of 30 pages.
Designing Objects and Making Classes
ObjectivesDefining a basic objectAdding attributes and methodsOrganizing classes into modules and packagesReadingPhillips, Chapter 223/27/2019
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?33/27/2019
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.43/27/2019
Creating a ClassTo define a class called use the following syntax: classClassName():#some more code here, indentedGood 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 digit53/27/2019
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 anything63/27/2019
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.73/27/2019
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>83/27/2019
Instantiating a ClassWhat’s up with the weird numbers/letters?