+ All Categories
Home > Documents > 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha...

1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha...

Date post: 26-Dec-2015
Category:
Upload: clifton-oliver
View: 230 times
Download: 0 times
Share this document with a friend
44
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer
Transcript
Page 1: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

1

Python Control of Flow and Defining Classes

LING 5200Computational Corpus LinguisticsMartha Palmer

Page 2: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

2

For Loops

Page 3: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides3

For Loops 1 A for-loop steps through each of the items in a

list, tuple, string, or any other type of object which the language considers an “iterator.”for <item> in <collection>:<statements>

When <collection> is a list or a tuple, then the loop steps through each element of the container.

When <collection> is a string, then the loop steps through each character of the string. for someChar in “Hello World”: print someChar

Page 4: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides4

For Loops 2

The <item> part of the for loop can also be more complex than a single variable name. When the elements of a container <collection>

are also containers, then the <item> part of the for loop can match the structure of the elements.

This multiple assignment can make it easier to access the individual parts of each element.

for (x, y) in [(a,1), (b,2), (c,3), (d,4)]:

print x

Page 5: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides5

For loops and range() function

Since we often want to range a variable over some numbers, we can use the range() function which gives us a list of numbers from 0 up to but not including the number we pass to it.

range(5) returns [0,1,2,3,4] So we could say:for x in range(5): print x

Page 6: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides6

Control of Flow

There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests. If Statements While Loops Assert Statements

Page 7: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides7

If Statements

if x == 3:print “X equals 3.”

elif x == 2:print “X equals 2.”

else:print “X equals something else.”

print “This is outside the ‘if’.”

Be careful! The keyword ‘if’ is also used in the syntax of filtered list comprehensions.

Page 8: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides8

If Statements – Another Ex.

x = ‘killer rabbit’if x == ‘roger’:

print “how’s jessica?”elif x == ‘bugs’:

print “What’s up, doc?”else:

print “Run away! Run away!”

Run away! Run away!

Page 9: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides9

While Loops

x = 3

while x < 10:

x = x + 1

print “Still in the loop.”

print “Outside of the loop.”

Page 10: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides10

While Loops, more examples

While 1:

print “Type Ctrl-C to stop me!”

x = ‘spam’

While x:

print x

x = x[1:]

‘spam’ ‘pam’ ‘am’ ‘m’

Page 11: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides11

Break and Continue

You can use the keyword break inside a loop to leave the while loop entirely.

You can use the keyword continue inside a loop to stop processing the current iteration of the loop and to immediately go on to the next one.

Page 12: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides12

While Loop with Break

while 1:

name = raw_input(‘Enter name:’)

if name == ‘stop’: break

age = raw_input(‘Enter age:’)

print ‘Hello’, name, ‘=>’,\

int(age)**2

Page 13: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides13

While Loop with Break, cont.

Enter name: melEnter age: 20Hello mel => 400

Enter name: bobEnter age: 30Hello, bob => 900

Enter name: stop

Page 14: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides14

While Loop with Continue

x = 10

while x:

x = x-1

if x % 2 != 0: continue #Odd? Skip print

print x

Page 15: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides15

Assert

An assert statement will check to make sure that something is true during the course of a program. If the condition if false, the program stops.

assert(number_of_players < 5)

if number_of_players >= 5:

STOP

Page 16: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

16

Logical Expressions

Page 17: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides17

True and False True and False are constants in Python.

Generally, True equals 1 and False equals 0. Other values equivalent to True and False:

False: zero, None, empty container or object True: non-zero numbers, non-empty objects.

Comparison operators: ==, !=, <, <=, etc. X and Y have same value: X == Y X and Y are two names that point to the same

memory reference: X is Y

Page 18: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides18

Boolean Logic Expressions

You can also combine Boolean expressions. True if a is true and b is true: a and b True if a is true or b is true: a or b True if a is false: not a

Use parentheses as needed to disambiguate complex Boolean expressions.

Page 19: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides19

Special Properties of And and Or

Actually ‘and’ and ‘or’ don’t return True or False. They return the value of one of their sub-expressions (which may be a non-Boolean value).

X and Y and Z If all are true, returns value of Z. Otherwise, returns value of first false sub-

expression. X or Y or Z

If all are false, returns value of Z. Otherwise, returns value of first true sub-expression.

Page 20: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides20

The “and-or” Trick There is a common trick used by Python

programmers to implement a simple conditional using ‘and’ and ‘or.’

result = test and expr1 or expr2 When test is True, result is assigned expr1. When test is False, result is assigned expr2. Works like (test ? expr1 : expr2) expression of C++.

But you must be certain that the value of expr1 is never False or else the trick won’t work.

I wouldn’t use this trick yourself, but you should be able to understand it if you see it

Page 21: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

21

Object Oriented Programmingin Python

Page 22: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides22

It’s all objects…

Everything in Python is really an object. We’ve seen hints of this already…“hello”.upper()list3.append(‘a’)dict2.keys()

You can also design your own objects… in addition to these built-in data-types.

In fact, programming in Python is typically done in an object oriented fashion.

Page 23: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

23

Defining Classes

Page 24: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides24

Defining a Class

A class is a special data type which defines how to build a certain kind of object. The ‘class’ also stores some data items that are

shared by all the instances of this class. ‘Instances’ are objects that are created which

follow the definition given inside of the class. Python doesn’t use separate class interface

definitions as in some languages. You just define the class and then use it.

Page 25: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides25

Methods in Classes

You can define a method in a class by including function definitions within the scope of the class block. Note that there is a special first argument self in all of the method definitions.

Note that there is usually a special method called __init__ in most classes.

We’ll talk about both later…

Page 26: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides26

Definition of student

class student:“““A class representing a student.”””def __init__(self,n,a): self.full_name = n self.age = adef get_age(self): return self.age

Page 27: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

27

Creating and Deleting Instances

Page 28: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides28

Instantiating Objects

There is no “new” keyword as in Java. You merely use the class name with ()

notation and assign the result to a variable.

b = student(“Bob Smith”, 21)

The arguments you pass to the class name are actually given to its .__init__() method.

Page 29: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides29

Constructor: __init__

__init__ acts like a constructor for your class. When you create a new instance of a class, this

method is invoked. Usually does some initialization work.

The arguments you list when instantiating an instance of the class are passed along to the __init__ method.

b = student(“Bob”, 21)

So, the __init__ method is passed “Bob” and 21.

Page 30: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides30

Constructor: __init__

Your __init__ method can take any number of arguments. Just like other functions or methods, the

arguments can be defined with default values, making them optional to the caller.

However, the first argument self in the definition of __init__ is special…

Page 31: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides31

Self

The first argument of every method is a reference to the current instance of the class. By convention, we name this argument self.

In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called. Similar to the keyword ‘this’ in Java or C++. But Python uses ‘self’ more often than Java uses

‘this.’

Page 32: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides32

Self

Although you must specify self explicitly when defining the method, you don’t include it when calling the method.

Python passes it for you automatically.

Defining a method: Calling a method:(this code inside a class definition.)def set_age(self, num): >>> x.set_age(23)

self.age = num

Page 33: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides33

No Need to “free”

When you are done with an object, you don’t have to delete or free it explicitly. Python has automatic garbage collection. Python will automatically detect when all of

the references to a piece of memory have gone out of scope. Automatically frees that memory.

Generally works well, few memory leaks. There’s also no “destructor” method for

classes.

Page 34: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

34

Access to Attributes and Methods

Page 35: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides35

Definition of student

class student:“““A class representing a student.”””def __init__(self,n,a): self.full_name = n self.age = adef get_age(self): return self.age

Page 36: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides36

Traditional Syntax for Access

>>> f = student (“Bob Smith”, 23)

>>> f.full_name # Access an attribute.

“Bob Smith”

>>> f.get_age() # Access a method.

23

Page 37: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides37

Accessing unknown members

What if you don’t know the name of the attribute or method of a class that you want to access until run time…

Is there a way to take a string containing the name of an attribute or method of a class and get a reference to it (so you can use it)?

Page 38: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides38

getattr(object_instance, string)

>>> f = student(“Bob Smith”, 23)

>>> getattr(f, “full_name”)“Bob Smith”

>>> getattr(f, “get_age”) <method get_age of class studentClass at 010B3C2>

>>> getattr(f, “get_age”)() # We can call this.23

>>> getattr(f, “get_birthday”) # Raises AttributeError – No method exists.

Page 39: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides39

hasattr(object_instance,string)

>>> f = student(“Bob Smith”, 23)

>>> hasattr(f, “full_name”)True

>>> hasattr(f, “get_age”)True

>>> hasattr(f, “get_birthday”)False

Page 40: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

40

Attributes

Page 41: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides41

Two Kinds of Attributes

The non-method data stored by objects are called attributes. There’s two kinds: Data attribute:

Variable owned by a particular instance of a class.Each instance can have its own different value for it.These are the most common kind of attribute.

Class attributes: Owned by the class as a whole. All instances of the class share the same value for it.Called “static” variables in some languages. Good for class-wide constants or for building counter of how many instances of the class have been made.

Page 42: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides42

Data Attributes You create and initialize a data attribute inside

of the __init__() method. Remember assignment is how we create variables

in Python; so, assigning to a name creates the attribute.

Inside the class, you refer to data attributes using self – for example, self.full_name

class teacher:“A class representing teachers.”def __init__(self,n): self.full_name = ndef print_name(self): print self.full_name

Page 43: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides43

Class Attributes All instances of a class share one copy of a class

attribute, so when any of the instances change it, then the value is changed for all of them.

We define class attributes outside of any method. Since there is one of these attributes per class

and not one per instance, we use a different notation: We access them using self.__class__.name notation.

class sample: >>> a = sample()x = 23 >>> a.increment()def increment(self): >>> a.__class__.x self.__class__.x += 1 24

Page 44: 1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.

LING 5200, 2006 BASED on Matt Huenerfauth’s

Python Slides44

Data vs. Class Attributes

class counter:overall_total = 0 # class attribute def __init__(self): self.my_total = 0 # data attributedef increment(self): counter.overall_total = \ counter.overall_total + 1 self.my_total = \ self.my_total + 1

>>> a = counter()>>> b = counter()>>> a.increment()>>> b.increment()>>> b.increment()>>> a.my_total1>>> a.__class__.overall_total3>>> b.my_total2>>> b.__class__.overall_total3


Recommended