CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming...

59
CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/

Transcript of CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming...

Page 1: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

CSE 399-004:Python Programming

Lecture 2: Data, Classes, and ModulesJanuary 22, 2007

http://www.seas.upenn.edu/~cse39904/

Page 2: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Administrative things

Page 3: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Teaching assistant

• Brian Summa (bsumma @ seas.upenn.edu)

• Office hours in Moore 100A (Linux lab)• Thursday 6 – 7pm• Friday 5:30 – 6:30pm

• He'll be doing a lot of the grading on homeworks• Talk to Brian S. first if you have a question about grading• If that doesn't work out, talk to me next

• Feel free to ask him questions, as well as me

3

Page 4: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Other announcements

• Homework 2 was due this morning

• Homework plans:• Homework 3 (Othello board) out by tomorrow• Homework 4 (Othello AI) out by next week• Both will be due two weeks from today

• My office hours: Wednesday 11–noon, 4:30–6pm

4

Page 5: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

cse39904submit

• You must submit all of your files every single timeyou use cse39904submit to turn in something

• You cannot submit things in bits and pieces

• cse39904submit -i hwX will list the files you have submitted for hwX

• cse39904submit -h tells you how to use it

5

Page 6: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Quick poll

• Would you rather there be a bulletin board for discussions, as in CSE 1xx, or would you rather use the email list?

• I'm going to insist that all discussions happen on exactly one of these things

6

Page 7: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

The view from here

Page 8: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

So far in this course

• One lecture: Crash-course introduction to Python• Basic datatypes• Basic control flow• How to run Python programs

• Two homeworks, which threw you in the ocean and asked you to swim (not so kind of me to do that…)

8

Page 9: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

The plan from here

• Next 3 lectures: Talk about Python itself• Everyone here comes from a wide range of backgrounds

• That leaves 9 lectures to talk about…• Python itself some more• Various Python libraries

• Somewhere in here, you'll start working on projects• Not sure what exactly will happen to homeworks• Lectures will continue

9

Page 10: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Data in Python

Page 11: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

What is a variable?

• All data in Python is represented by objects

• Then variables must all be references to objects

• That is, the memory a variable takes up is merely a pointer to some other part of memory that actually has the object

• We usually think of the thing being pointed to as the value of the variable, not the pointer itself

11

Page 12: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

>>> q = [2, 3]>>> p = [1, q, 4]>>> print p[1, [2, 3], 4]>>> q[0] = 42>>> print q[42, 3]>>> print p[1, [42, 3], 4]

q

2 3

The integers should also be pointers, but they're immutable, so it doesn't

really matter.

Page 13: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

>>> q = [2, 3]>>> p = [1, q, 4]>>> print p[1, [2, 3], 4]>>> q[0] = 42>>> print q[42, 3]>>> print p[1, [42, 3], 4]

q

2 3

p

1 4

Page 14: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

>>> q = [2, 3]>>> p = [1, q, 4]>>> print p[1, [2, 3], 4]>>> q[0] = 42>>> print q[42, 3]>>> print p[1, [42, 3], 4]

q

42 3

p

1 4

Page 15: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

>>> q = [2, 3]>>> p = (1, q, 4)>>> print p(1, [2, 3], 4)>>> q[0] = 42>>> print q[42, 3]>>> print p(1, [42, 3], 4)>>> p[2] = 100(... error messages ...)TypeError: 'tuple' object does not support item assignment

Notice what it means for a tuple to be immutable!

q

42 3

p

1 4

Page 16: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Classes: The basics

Page 17: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Object-oriented programming (OOP)

• Based on the survey results, it seems safe to assume that everyone here knows what OOP is

• Terminology like the following should be familiar:• Class• Inheritance• Subclass / superclass• Instances / objects• Methods (instance and static)• Instance variables• Derived class / Base class

17

Page 18: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Some differences from Java

• Everything in a class is public

• No overloading — Use optional arguments• Don't confuse this with overriding

• Derived classes may have multiple base classes• This is known as "multiple inheritance"• You should avoid this when possible

• No super

18

Page 19: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Aside: New-style versus Classic-style

• Basic idea: there should be no distinction between built-in types and user-defined classes

• I'll try to highlight some of the differences between the two styles of classes

• It's unlikely you'll come out today with any real appreciation of what makes them different

• Just be aware that Python is in the process of transitioning to the new-style classes

19

Page 20: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Basic structure of a class definition

• Defines a class Derived which inherits from base classes Base1 and Base2

• Derived will be a new-style class if it inherits from a new-style class and classic-style otherwise

20

class Derived(Base1, Base2): "Documentation string." <statements>

Page 21: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Basic structure of a class definition

• You can specify no base classes, in which case you get a classic-style class

• You can specify the base class object if you want a new-style class that inherits as little as possible

21

class Derived(Base1, Base2): "Documentation string." <statements>

Page 22: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Constructors

22

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j

>>> a = Pair(2, 3)>>> print a<__main__.Pair instance at 0x67300>

Page 23: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Constructors

22

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j

>>> a = Pair(2, 3)>>> print a<__main__.Pair instance at 0x67300>

like Java, but no new needed

Page 24: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Constructors

22

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j

>>> a = Pair(2, 3)>>> print a<__main__.Pair instance at 0x67300>

the constructor of a class is called __init__

Page 25: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Constructors

22

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j

>>> a = Pair(2, 3)>>> print a<__main__.Pair instance at 0x67300>

Did you notice that __init__ takes 3 arguments, but we constructed an instance by only giving 2? And no optional arguments either!

Page 26: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self

23

• The first argument of the constructor or a method in a class is usually called self

• It corresponds to this in Java

• Since Python has no variable declarations, you need an explicit means of assigning to instance variables

• self provides you means of doing exactly that• It also lets you call methods on the current instance

Page 27: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

• The assignments here assign to two variables fst and snd which are local to __init__

• Calling get_first() would result in an error

24

class Pair(): def __init__(self, i, j): fst = i snd = j def get_first(): return fst

Page 28: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

25

class Pair(): def __init__(self, i, j): fst = i snd = j def get_first(): return fst

>>> a = Pair(2, 3)>>> a.get_first()(... error messages ...)TypeError: get_first() takes no arguments (1 given)

Page 29: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

25

class Pair(): def __init__(self, i, j): fst = i snd = j def get_first(): return fst

>>> a = Pair(2, 3)>>> a.get_first()(... error messages ...)TypeError: get_first() takes no arguments (1 given)

method invocation uses familiar dot notation

Page 30: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

25

class Pair(): def __init__(self, i, j): fst = i snd = j def get_first(): return fst

>>> a = Pair(2, 3)>>> a.get_first()(... error messages ...)TypeError: get_first() takes no arguments (1 given)

no self argument

namely, the instance

Page 31: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

26

class Pair(): def __init__(self, i, j): fst = i snd = j def get_first(self): return fst

>>> a = Pair(2, 3)>>> a.get_first()(... error messages ...)NameError: global name 'fst' is not defined

Page 32: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

26

class Pair(): def __init__(self, i, j): fst = i snd = j def get_first(self): return fst

>>> a = Pair(2, 3)>>> a.get_first()(... error messages ...)NameError: global name 'fst' is not defined

should get this from self

should assign these via self

Page 33: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

27

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j def get_first(self): return self.fst

>>> a = Pair(2, 3)>>> a.get_first()2>>> a.fst2

Page 34: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Self (continued)

27

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j def get_first(self): return self.fst

>>> a = Pair(2, 3)>>> a.get_first()2>>> a.fst2

everything is public

Page 35: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Basic rules of thumb

28

• Instance variables are referred to through self• For example: self.foo

• Methods and constructors must take at least one argument, which is called self

Page 36: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Basic rules of thumb

28

• Instance variables are referred to through self• For example: self.foo

• Methods and constructors must take at least one argument, which is called self

Technically, you can call it anything you want. The convention is to call it self.Also ignoring static methods (for now).

Page 37: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

instanceof

• instanceof(obj, cls)• Return True if obj is an instance of cls• Returns False otherwise

• Works pretty much as you might expect

29

Page 38: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Single inheritance

• Works much as it did in Java

• Catch #1: Super class constructor is not called automatically (call it yourself if need be)

• Catch #2: No super in Python• Use BaseClass.foo to refer to superclass attributes• If you call super class methods like this, you have to pass

in self yourself!

30

Page 39: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Single inheritance (example)

31

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j def get_first(self): return self.fst

class SillyPair(Pair): def get_first(self): return Pair.get_first(self) + 50 def get_second(self): return self.get_first() + self.snd

>>> a = SillyPair(2, 3)>>> a.get_second()55>>> a.get_first()52

Page 40: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Single inheritance (example)

31

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j def get_first(self): return self.fst

class SillyPair(Pair): def get_first(self): return Pair.get_first(self) + 50 def get_second(self): return self.get_first() + self.snd

>>> a = SillyPair(2, 3)>>> a.get_second()55>>> a.get_first()52

constructor inherited, just like any other method

Page 41: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Single inheritance (example)

31

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j def get_first(self): return self.fst

class SillyPair(Pair): def get_first(self): return Pair.get_first(self) + 50 def get_second(self): return self.get_first() + self.snd

>>> a = SillyPair(2, 3)>>> a.get_second()55>>> a.get_first()52

call the superclass's version

Page 42: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Single inheritance (example)

31

class Pair(): def __init__(self, i, j): self.fst = i self.snd = j def get_first(self): return self.fst

class SillyPair(Pair): def get_first(self): return Pair.get_first(self) + 50 def get_second(self): return self.get_first() + self.snd

>>> a = SillyPair(2, 3)>>> a.get_second()55>>> a.get_first()52

call a method on the current instance

Page 43: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Modules: The basics

Page 44: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

What is a module?

• Basic problems in programming Python:• Typing things into the interpreter repeatedly gets old• You want to reuse code that someone else has written

• Modules provide a basic way of organizing code

• A module mod is simply a Python file mod.py,i.e., "module" is just another name for a Python file

33

Page 45: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Loading modules

• import foo will import the module foo, which should be in the file foo.py

• What import foo does:• If foo has already been imported, do nothing• Otherwise, search for the file foo.py in the search path

• By default, the search path includes the current working directory and the standard library directories

• For now, put your modules in the current directory

34

Page 46: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Loading modules

• import foo will import the module foo, which should be in the file foo.py

• What import foo does:• If foo has already been imported, do nothing• Otherwise, search for the file foo.py in the search path• Parse foo.py, raise an exception if there is a syntax error• Otherwise, add foo to the list of imported modules

• The interpreter keeps track of all imported modules

35

Page 47: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Loading modules

• import foo will import the module foo, which should be in the file foo.py

• What import foo does:• If foo has already been imported, do nothing• Otherwise, search for the file foo.py in the search path• Parse foo.py, raise an exception if there is a syntax error• Otherwise, add foo to the list of imported modules• Execute the code in foo.py

36

Page 48: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

"Executing" a module

• About that last step: what does it mean?

• Each loaded module has a symbol table which contains entries for every name it defines

• Each statement is executed, and if necessary, an entry is added to the symbol table

37

Page 49: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Saving some typing

• from mod import foo, bar, baz• Lets you use foo, bar, baz without typing "mod."

• from mod import *• Lets you use anything from mod without typing "mod."

38

Page 50: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Saving some typing

• from mod import foo, bar, baz• Lets you use foo, bar, baz without typing "mod."

• from mod import *• Lets you use anything from mod without typing "mod."

38

a lie, but it's good enough

for now

Page 51: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Saving some typing

• from mod import foo, bar, baz• Lets you use foo, bar, baz without typing "mod."

• from mod import *• Lets you use anything from mod without typing "mod."

38

>>> import sys>>> sys.stdout.write("Hello!\n")Hello!>>> sys.modules{'copy_reg': <module 'copy_reg' from ...

Page 52: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Saving some typing

• from mod import foo, bar, baz• Lets you use foo, bar, baz without typing "mod."

• from mod import *• Lets you use anything from mod without typing "mod."

39

>>> from sys import stdout>>> stdout.write("Hello!\n")Hello!>>> modules(... error messages ...)NameError: name 'modules' is not defined

Page 53: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Saving some typing

• from mod import foo, bar, baz• Lets you use foo, bar, baz without typing "mod."

• from mod import *• Lets you use anything from mod without typing "mod."

40

>>> from sys import *>>> stdout.write("Hello!\n")Hello!>>> modules{'copy_reg': <module 'copy_reg' from ...

Page 54: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Saving some typing

41

>>> from sys import *>>> sys.stdout.write("Hello!\n")Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'sys' is not defined

The from forms of import don't define the module name!

Page 55: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Tips about importing modules

42

• Python evaluates the contents of a module onlythe first time it's imported

• Avoid from mod import * when possible• It clutters the namespace• It becomes difficult to determine who defined what

Page 56: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Modules as programs

• Many tools for Python import modules so that they can analyze them

• Therefore, it is a bad idea if non-trivial code gets executed when a module is imported

• For example:

43

def foo(): return 42

print "Hello!"

not a good idea

Page 57: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

• If you're "running" a file bar.py as a program, then in that case, bar.__name__ will be '__main__'.

Modules as programs

44

>>> import bar>>> bar.__name__'bar'

def foo(): return 42

if __name__ == "__main__": print "Hello!"

bar.py

Page 58: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

• If you're "running" a file bar.py as a program, then in that case, bar.__name__ will be '__main__'.

def foo(): return 42

if __name__ == "__main__": print "Hello!"

bar.py

Modules as programs

45

prompt$ python bar.pyHello!

Page 59: CSE 399-004: Python Programming - Penn …cse39904/lectures/02-Data...Basic problems in programming Python: • Typing things into the interpreter repeatedly gets old • You want

Next time

• More on classes• Scoping and namespaces in Python

• Times after that:• Review some basic datatypes and constructs• Exceptions• Generators (?)• Iterators (?)

46