CSL02-MakingClasses.pdf - Designing and Creating Classes...

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

Designing and Creating Classes
Objectives Defining a basic class Constructors Adding instance attributes and methods Adding class (static) attributes and methods Defining a public interface Executing modules as scripts 2 CS 172 - Drexel University 4/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? 3 CS 172 - Drexel University 4/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 do Identify useful methods More likely than not you’ll end up adding attributes and methods as you go. 4 CS 172 - Drexel University 4/17/2020
Creating a Class To define a class called use the following syntax: class ClassName (): #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, underscores No special characters Do not begin with a digit 5 CS 172 - Drexel University 4/17/2020
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 CS 172 - Drexel University 4/17/2020
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 CS 172 - Drexel University 4/17/2020
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> 4/17/2020 CS 172 - Drexel University 8
Instantiating a Class What’s up with the weird numbers/letters? <lecture2.MyFirstClass object at 0x1021f9e48> <lecture2.MyFirstClass object at 0x1021f9ef0> Well, a and b are just objects, so what does it mean to print out an entire object?

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture