Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer."— Presentation transcript:

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

2 2 For Loops

3 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 3 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 in : When is a list or a tuple, then the loop steps through each element of the container. When is a string, then the loop steps through each character of the string. for someChar in “Hello World”: print someChar

4 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 4 For Loops 2 The part of the for loop can also be more complex than a single variable name.  When the elements of a container are also containers, then the 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

5 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 5 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

6 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 6 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

7 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 7 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.

8 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 8 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!

9 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 9 While Loops x = 3 while x < 10: x = x + 1 print “Still in the loop.” print “Outside of the loop.”

10 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 10 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’

11 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 11 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.

12 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 12 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

13 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 13 While Loop with Break, cont. Enter name: mel Enter age: 20 Hello mel => 400 Enter name: bob Enter age: 30 Hello, bob => 900 Enter name: stop

14 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 14 While Loop with Continue x = 10 while x: x = x-1 if x % 2 != 0: continue#Odd? Skip print print x

15 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 15 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

16 16 Logical Expressions

17 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 17 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

18 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 18 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.

19 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 19 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.

20 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 20 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

21 21 Object Oriented Programming in Python

22 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 22 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.

23 23 Defining Classes

24 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 24 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.

25 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 25 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…

26 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 26 Definition of student class student: “““A class representing a student.””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age

27 27 Creating and Deleting Instances

28 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 28 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.

29 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 29 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.

30 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 30 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…

31 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 31 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.’

32 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 32 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

33 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 33 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.

34 34 Access to Attributes and Methods

35 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 35 Definition of student class student: “““A class representing a student.””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age

36 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 36 Traditional Syntax for Access >>> f = student (“Bob Smith”, 23) >>> f.full_name # Access an attribute. “Bob Smith” >>> f.get_age() # Access a method. 23

37 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 37 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)?

38 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 38 getattr(object_instance, string) >>> f = student(“Bob Smith”, 23) >>> getattr(f, “full_name”) “Bob Smith” >>> getattr(f, “get_age”) >>> getattr(f, “get_age”)() # We can call this. 23 >>> getattr(f, “get_birthday”) # Raises AttributeError – No method exists.

39 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 39 hasattr(object_instance,string) >>> f = student(“Bob Smith”, 23) >>> hasattr(f, “full_name”) True >>> hasattr(f, “get_age”) True >>> hasattr(f, “get_birthday”) False

40 40 Attributes

41 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 41 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.

42 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 42 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 = n def print_name(self): print self.full_name

43 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 43 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 += 124

44 LING 5200, 2006 BASED on Matt Huenerfauth’s Python Slides 44 Data vs. Class Attributes class counter: overall_total = 0 # class attribute def __init__(self): self.my_total = 0 # data attribute def 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_total 1 >>> a.__class__.overall_total 3 >>> b.my_total 2 >>> b.__class__.overall_total 3


Download ppt "1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer."

Similar presentations


Ads by Google