L02-MakingClasses.pdf - Designing Objects and Making...

This preview shows page 1 - 10 out of 30 pages.

Designing Objects and Making Classes
Objectives Defining a basic object Adding attributes and methods Organizing classes into modules and packages Reading Phillips, Chapter 2 2 3/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? 3 3/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 do Identify useful methods More likely than not you’ll end up adding attributes and methods as you go. 4 3/27/2019
Creating a Class To define a class called use the following syntax: class ClassName (): #some more code here, indented 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, underscores No special characters Do not begin with a digit 5 3/27/2019
Creating a Class - Example Lets define a very basic class called MyFirstClass : class MyFirstClass(): pass Note: pass is a Python keyword indicating no further work is to be done in this block So we created a class that does not do anything 6 3/27/2019
Creating a Class - Example But 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 script However, often the purpose of defining classes is to create re-usable object So it may make more sense to put it in its own file and import it. 7 3/27/2019
Instantiating a Class Now we can use our class! Assuming the MyFirstClass definition was put within the file lecture2.py from lecture2 import MyFirstClass a = MyFirstClass() b = MyFirstClass() print(a) print(b) Here is the output: >>> %Run myFirstClassTest.py <lecture2.MyFirstClass object at 0x1021f9e48> <lecture2.MyFirstClass object at 0x1021f9ef0> 8 3/27/2019
Instantiating a Class What’s up with the weird numbers/letters?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture