The End Harry Smithcis192/html/files/lec/week13/lec13.pdf · When to Use Singleton Pattern File I/O...

Post on 21-Jul-2020

1 views 0 download

Transcript of The End Harry Smithcis192/html/files/lec/week13/lec13.pdf · When to Use Singleton Pattern File I/O...

CIS192 Python ProgrammingThe End

Harry Smith

University of Pennsylvania

April 19, 2018

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 1 / 27

Outline

1 Good Design in PythonABCs of PythonSingletonObserverMementoCIS 192 in ReviewNext Steps

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 2 / 27

The abc module

Stands for the "Abstract Base Class" moduleUseful for giving a template for how some object should behaveRequires some methods to be implemented separately, somecome pre-packaged

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 3 / 27

Defining an ABC

Use the ABCMeta class from abc

from abc import ABCMetaclass MyClass(metaclass=ABCMeta):

...

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 4 / 27

Specifying abstract methods

Use the ABCMeta class from abc

import abcclass MyClass(metaclass=abc.ABCMeta):

@abc.abstractmethoddef task():raise NotImplementedError()

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 5 / 27

Can include partially complete abstract methods

import abcclass MyClass(metaclass=abc.ABCMeta):

@abc.abstractmethoddef partial_task(x):x.sort()

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 6 / 27

...or fully implemented methods

import abcclass MyClass(metaclass=abc.ABCMeta):

def complete_task(x):print(x)

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 7 / 27

Subclassing (registering)Use the register method gained from the ABCMeta

import abcfrom abc_base import MyClass

@MyClass.registerclass SubClass():

def task():print("Completed task!")

def partial_task(x):super().partial_task(x)print(x[0])

>>> s = SubClass()>>> s.task()"Completed task!">>> s.complete_task("hi")"hi">>> s.partial_task([3, 2])2

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 8 / 27

Singleton Pattern

What if I need exactly one instance of something?How can I guarantee that I’m always getting the one thing?Why is this important?

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 9 / 27

When to Use Singleton Pattern

File I/OMultithreaded operationsDistributed Computing

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 10 / 27

Singleton: Main Idea

Define an inner class for a given objectLet the inner class handle the behaviorLet the outer class check if the inner class has already beencreated

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 11 / 27

Observer Pattern

What if I have a many-to-one relation of objects?How can I guarantee that each of the many objects are kept up todate?

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 12 / 27

When to Use Observer Pattern

Controlling sub-processes or other instancesSyncing up multiple instances / usersDisplaying server status

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 13 / 27

Observer: Main Idea

Let the "one" object inherit from a Notifier classLet the "many" classes inherit from an Observer classOn association, let the notifier store a pointer to observerOn system update, let the notifier send a message to eachobserver

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 14 / 27

Memento Pattern

What happens when I might enter an illegal state in my program?How can I procedurally store, observe, and revert to programstates?

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 15 / 27

When to Use Memento Pattern

When the legality of some operation cannot be thoroughlychecked before executionWhen race conditions are observable but unavoidableTo programmatically keep track of state

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 16 / 27

Memento: Main Idea

Write a "memento" class that is a simple wrapper around someparticular stateExtend the vulnerable/interesting class to have diary and backupmethodsBefore risky operations, or at predetermined periods, write amemento objectWhen a problem is encountered, revert the class using statestored in Memento.

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 17 / 27

Python Basics & FundamentalsFunctional ProgrammingObject-Oriented ProgrammingIterators, Generators, Exceptions & IORegular Expressions & Other ModulesHTTP Requests / HTML ParsingData AnalysisMachine LearningNatural Language ProcessingWeb AppsArtificial IntelligenceProbability & Simulations

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 18 / 27

If there’s anything I want you to remember...Generators! Use this space-efficient tool in place of iterators.Lambdas & Functional Programming: they look scary but areincredibly useful

I ComparatorsI Elements of good design: strategy design pattern

Make your own classes!Using "with open ... as f:" to safely open files!List/Set/Generator ComprehensionsDictionariesUse pip, installing binaries, and taking advantage of librariesThe power of Python function headers (default kwargs, arbitrarilymany positional args).Testing code is easyUse Decorators to avoid repeating yourselfPython is excellent for scripting. It’s very useful for solving simplemath/probability problems.Python makes coding fun.

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 19 / 27

Scratching the Surface

Each special topic has MUCH more depth than what we’vecovered this semester.Many topics we haven’t mentioned

I Parallel & Distributed ComputingI ConcurrencyI Graphical User InterfacesI etc.

Check the website for access to some of these.

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 20 / 27

What’s Next?

I hope you find the skills you’ve acquired from CIS 192 useful!Build your own side-projects, big or small!Learn more about Python!

I PyCon conference recordingsI Obey the Testing Goat (TDD in Python + Web Dev)I New Coder: practical tutorials in Python

Join the Python community!/r/Python subredditTrending GitHub Python repositoriesStackOverflow Python questions

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 21 / 27

What *Isn’t* Next?

Build a game!I PyGame bookI More rudimentary game advice

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 22 / 27

What *Isn’t* Next?

Manage a database!I Advice on database management

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 23 / 27

What *Isn’t* Next?

Learn Django!I Django TutorialI Mozilla’s Guides (very nice)

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 24 / 27

What *Isn’t* Next?

Deploy Applications!I Fabric (for SSH/sysadmin)I Launch Flask Apps on AWSI Launch Django Apps on AWS

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 25 / 27

What *Isn’t* Next?

Build an interpreterWrite your own programming languageBuild a theorem proverAutomate boring computer tasksScrape the webDo beautiful data analysisGenerate other code automaticallyHandle 3D animation and modeling in MayaSend emails automaticallyQuickly create UIBuild maps and GISControl trafficSimulate drug action

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 26 / 27

Thank You

Harry Smith (University of Pennsylvania) CIS 192 April 19, 2018 27 / 27