Title: Python Control of Flow and Defining Classes
1Python Control of Flow and Defining Classes
- LING 5200
- Computational Corpus Linguistics
- Martha Palmer
2For Loops
3For 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 ltitemgt in ltcollectiongtltstatementsgt
- When ltcollectiongt is a list or a tuple, then the
loop steps through each element of the container. - When ltcollectiongt is a string, then the loop
steps through each character of the string. - for someChar in Hello World
- print someChar
4For Loops 2
- The ltitemgt part of the for loop can also be more
complex than a single variable name. - When the elements of a container ltcollectiongt are
also containers, then the ltitemgt 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
5For 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 sayfor x in range(5) print x
6Control 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
7If 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.
8If Statements Another Ex.
- x killer rabbit
- if x roger
- print hows jessica?
- elif x bugs
- print Whats up, doc?
- else
- print Run away! Run away!
- Run away! Run away!
9While Loops
- x 3
- while x lt 10
- x x 1
- print Still in the loop.
- print Outside of the loop.
10While Loops, more examples
- While 1
- print Type Ctrl-C to stop me!
- x spam
- While x
- print x
- x x1
- spam pam am m
11Break 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.
12While Loop with Break
- while 1
- name raw_input(Enter name)
- if name stop break
- age raw_input(Enter age)
- print Hello, name, gt,\
- int(age)2
13While Loop with Break, cont.
- Enter name mel
- Enter age 20
- Hello mel gt 400
- Enter name bob
- Enter age 30
- Hello, bob gt 900
- Enter name stop
14While Loop with Continue
- x 10
- while x
- x x-1
- if x 2 ! 0 continue Odd? Skip print
- print x
-
15Assert
- 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 lt 5)
- if number_of_players gt 5
- STOP
16Logical Expressions
17True 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 , !, lt, lt, 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
18Boolean 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.
19Special Properties of And and Or
- Actually and and or dont 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.
20The 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 wont work. - I wouldnt use this trick yourself, but you
should be able to understand it if you see it
21Object Oriented Programmingin Python
22Its all objects
- Everything in Python is really an object.
- Weve seen hints of this alreadyhello.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.
23Defining Classes
24Defining 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 doesnt use separate class interface
definitions as in some languages. You just
define the class and then use it.
25Methods 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. - Well talk about both later
26Definition of student
- class studentA class representing a
student.def __init__(self,n,a)
self.full_name n self.age adef
get_age(self) return self.age
27Creating and Deleting Instances
28Instantiating 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.
29Constructor __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.
30Constructor __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
31Self
- 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.
32Self
- Although you must specify self explicitly when
defining the method, you dont 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) gtgtgt x.set_age(23)self.ag
e num
33No Need to free
- When you are done with an object, you dont 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.
- Theres also no destructor method for classes.
34Access to Attributes and Methods
35Definition of student
- class studentA class representing a
student.def __init__(self,n,a)
self.full_name n self.age adef
get_age(self) return self.age
36Traditional Syntax for Access
- gtgtgt f student (Bob Smith, 23)
- gtgtgt f.full_name Access an attribute.
- Bob Smith
- gtgtgt f.get_age() Access a method.
- 23
37Accessing unknown members
- What if you dont 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)?
38getattr(object_instance, string)
- gtgtgt f student(Bob Smith, 23)
- gtgtgt getattr(f, full_name)
- Bob Smith
- gtgtgt getattr(f, get_age)
- ltmethod get_age of class studentClass at
010B3C2gt - gtgtgt getattr(f, get_age)() We can call this.
- 23
- gtgtgt getattr(f, get_birthday)
- Raises AttributeError No method exists.
39hasattr(object_instance,string)
- gtgtgt f student(Bob Smith, 23)
- gtgtgt hasattr(f, full_name)
- True
- gtgtgt hasattr(f, get_age)
- True
- gtgtgt hasattr(f, get_birthday)
- False
40Attributes
41Two Kinds of Attributes
- The non-method data stored by objects are called
attributes. Theres 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.
42Data 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 teacherA class representing
teachers.def __init__(self,n)
self.full_name ndef print_name(self)
print self.full_name
43Class 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 gtgtgt a sample()x 23 gtgtgt
a.increment()def increment(self) gtgtgt
a.__class__.x self.__class__.x 1 24
44Data vs. Class Attributes
- class counteroverall_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
gtgtgt a counter()gtgtgt b counter()gtgtgt
a.increment()gtgtgt b.increment()gtgtgt
b.increment()gtgtgt a.my_total1gtgtgt
a.__class__.overall_total3gtgtgt b.my_total2gtgtgt
b.__class__.overall_total3