Python’ - OS3Perl’vs.’Python’ • Perl is worse than Python because people wanted it worse....
Transcript of Python’ - OS3Perl’vs.’Python’ • Perl is worse than Python because people wanted it worse....
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, FuncEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented python 8. DocumentaEon
IntroducEon
• WriUen by Guido van Rossum • Started work in 1990 • First release in 1991 • Minor number release every 6 months • Named aZer Monty Python
“Perl is executable line noise. Python is executable pseudo-‐code.”
What is Python
• a general-‐purpose high-‐level programming language whose design philosophy emphasizes code readability.
• Python aims to combine "remarkable power with very clear syntax”, and its standard library is large and comprehensive.
• Its use of indentaEon for block delimiters is unusual among popular programming languages.
hUp://en.wikipedia.org/wiki/Python_%28programming_language%29
Perl vs. Python
• Perl is worse than Python because people wanted it worse. Larry Wall, 14 Oct 1998
• I would actively encourage my competition
to use Perl. Sean True, 30 Mar 1999
• if you look at from 10 KM above, perl, python, and ruby are the same … guido van rossum , pycon-2012
Why I Love Python ©2001 www.BruceEckel.com
Last news about Python from Guido van Rossum
• Keynote: Guido Van Rossum given at pycon-‐2012 (Same talk was given at the UvA last July) – Trolls: a quesEon that isn’t meant as a quesEon, but to heckle • “Python Sucks. Ruby Rules” • “When will you admit Python 3 is a mistake?” • “Since PyPy is so much faster than CPython, why not abandon CPython”
• Etc.
Notes: hUps://andrew-‐schoen-‐pycon-‐2012-‐notes.readthedocs.org/en/latest/sunday/keynote.html
Video: hUp://ontwik.com/python/pycon-‐2012-‐keynote-‐guido-‐van-‐rossum/
10 Reasons to Learn the Python Programming Language
1. Reduced CluUer 2. It’s not backward-‐compa5ble in exchange for pain 3. It doesn’t value performance over your produc5vity 4. It doesn’t treat you like stupid 5. I don’t wait forever for a full implementa5on of the
language 6. It doesn’t make assump5ons about how we discover
errors 7. MarkeEng people are not involved 8. You don’t have to type so much 9. your guesses are usually right 10. Python lets you focus on concepts
Why I Love Python ©2001 www.BruceEckel.com
DocumentaEon : Python (where to go beyond the slides to learn …)
hUp://python.org/about/gepngstarted/ $ pydoc -‐g
• PyPI -‐ the Python Package Index
• SIG for Python Resource Cataloguing
DocumentaEon : Pydoc Commandline
$ pydoc sys!!
Web browser: • pydoc start an HTTP server on the
local machine that will serve documentaEon to visiEng Web browsers.
# start a HTTP server on ! #port 1234! $ pydoc-p 1234 !! ! # start the server and ! #additionally bring up a small! $ pydoc -g !
!
Simple Python
A simple program to start with: #!/usr/bin/python principal = 1000 # initial amount rate = 0.05 # interest rate numyears = 5 # number of years year = 1 while year <= numyears: principal = principal*(1+rate) print year, principal year += 1
The Python Interpreter • Normal method for scripEng using
#!/usr/bin/python
• python is also an interacEve interpreter you can interpret single lines of code good for simple checking and debugging
$ python mypythonprogram.py!
$ python![GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin!
Type "help", "copyright", "credits" or "license" for more information.!
>>> !
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, FuncEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented Python 8. DocumentaEon
Variables
• Python is a dynamically typed language: names can represent values of different types during the execuEon of the program.
• Names or idenEfiers – must begin with a non-‐numeric character or underscore – but may contain both numeric and non-‐numeric characters
Troll about dynamic type “I don’t want my app to fail witn an A9ributeError a;er running for 4 hours”
Dynamic types (Weak typing)
• “You write what you want to do, let Python worry about how”
• weakly typed programming languages are those that support implicit type conversion
• Argument for – dynamic typing is that it requires less effort on the part of the programmer, because the interpreter implicitly performs certain conversions
• Argument against – dynamic typing: “errors won’t be found”
Variables: Numbers (1) simple numbers the same as with perl: • decimal: 12, -17, 255, … • octal, start with 0: 015, -023, 0777, … • hexadecimal, start with 0x: 0xc, -0x11, 0xff,…
floaEng point numbers: • ”one and a quarter": 1.25 But also imaginary numbers: • wriUen as 'numberj', for example: 1.23j
Variables: Numbers (2)
• Complex numbers, using imaginary numbers: – wriUen as: num1 + num2j, – or can be created with: complex(real, imag) funcEon.
(1.0j * 1J) è (-1+0j)
Variables: Strings (1)
• To create string literals, enclose them in single, double or triple quotes.
Examples: 'Hello World' "Python is groovy"
"""Sino si Pepito Biglangliko?"""
• The same type of quote used to start the string must be used to terminate it.
Variables: String (2)
• Escape sequences represent special characters: \n, \t, . . .
• Both in double quoted (") and single quoted (') strings
• For verba5m strings use raw strings using r'. . . ' >>> print "Hi there! \n \t It's me.\n" Hi there!
It's me.
>>> print r'And me \n \t as well!' And me \n \t as well!
Variables: Strings (3) • Triple-‐quoted strings using either """or ‘’’ capture all the
text that appears before the terminaEng triple quote.
– Single and double quoted strings must be on one logical line. – Triple-‐quoted strings are useful when contents of the string span
mul5ple lines of text.
– For example: >>> print """ … Usage: thingy [OPTIONS] … -h Display this usage message … -H hostname Hostname to connect to …"""
• String literals can span mul5ple lines using a closing backslash ('\')
• The backslash is for syntax purposes only, it is not included in the output
>>> print "Hi \ … there! \n\ … \t It's me.\n”
prints: Hi there! It's me.
Variables: Strings (4)
Variables: Strings (5) • Strings are indexed like lists, starEng at 0 • You can use them using the index operator '[i]'
>>> a = "Hello World" >>> b = a[4] >>> b o
• Substrings can be used by slicing: `[i:j]’ >>> a[0:6] "Hello " >>> d = a[7:] "World" >>> e = a[3:8] "lo Wo"
Variables: Strings (6)
Other data types can be converted into a string using either str() or repr() funcEons or backquotes (`), which are a shortcut notaEon for repr().
Examples
>>> x = 5.2 >>> s = "The value of x is " + str(x) >>> s The value of x is 5.2
>>> s = "The value of y is " + repr(y) >>> s = "The value of y is " + `y`
Operators: numbers
• The following operators for numbers apply: +, -, *, /, //, % …
• Binary operators: C-‐style shiZing & masking 1<<16, x&0xff, x|1, ~x, x^y • Integer division truncates
• 1/2 -‐> 0 # 1./2. -‐> 0.5, float(1)/2 -‐> 0.5 \\ >>> width = 20 >>> height = 5*9
>>> width * height 900
Operators: Strings
• Strings can be concatenated using a '+' • But also by wriEng them adjacent to each other:
Examples >>> print "Hello" + 'Python' HelloPython >>> print "Python " "says" ' Hello!'
Python says Hello!
Reference SemanEcs
• Assignment manipulates references • x = y does not make a copy of y • x = y makes x reference the object y references
• Very useful; but beware! • Example:
>>> a = [1, 2, 3] >>> b = a >>> a.append(4) >>> print b [1, 2, 3, 4]
a
1 2 3
b
a
1 2 3
b
4
a = [1, 2, 3]
a.append(4)
b = a
a 1 2 3
Slide 25 ©2001, 2002 Guido van Rossum
a
1
b
a
1 b
a = 1
a = a+1
b = a
a 1
2
Changing an Integer
old reference deleted by assignment (a=...)
new int object created by add operator (1+1)
Slide 26 ©2001, 2002 Guido van Rossum
Play around 1
• Write a short python prog, which when you enter our name it prints : Hi ! <your name> .
• Hint: use raw_input() to get the input
>>> name = raw_input('What is your name?\n')
>>> What is your name? OS3
>>> print 'Hi, ' + name + '.' Hi, OS3.
Variables: Lists (1) • lists and tuples are sequences of arbitrary objects You
can create a list as follows: >>> names = [ "Eric", "Trixie", "Coley" ]
They too are indexed: >>> a = names[2] a is now "Coley" >>> names[0] = ”Jan" >>> names[0] Jan
• append a new member to the end of a list using append() >>> names.append("Khamir") >>> names [ "Eric", "Trixie", "Coley", "Khamir" ]
Variables: Lists (2) • You can extract or reassign a por5on of a list by using the slicing
operator. Examples
>>> names = ["pusakat","Trixie","Coley","Khamir"] >>>names[0:2]
["pusakat", "Trixie”] >>> names[2:]
["Coley", "Khamir" ]
• Use the plus ('+') operator to concatenate lists.
>>> a = [1,2,3] + [4,5] >>> a [1,2,3,4,5]
Variables: Lists (3) • Lists can contain any kind of Python object including
other lists.
Example: >>> a = [1,"Dave”,3,["Mark”,9,[100, 101]],10]
• Nested lists are accessed as follows: >>> a[1] "Dave" >>> a[3] ['Mark', 9, [100, 101]] >>> a[3][2][1] 101
Variables: Tuples
• Tuples are a lot like lists – Tuples support most of the same funcEons as a list – They are however immutable aZer creaEon – Used to return mul5ple values from a funcEon
• You can create tuples by enclosing a group of values in parentheses ('(. . . )') or with a comma-‐separated list.
>>> a = (1,4,5,-9,10,'hello!’) >>> b = (7,) # this is a singleton >>> c = a, b >>> c ((1,4,5,-9,10,'hello!’),(7,))
Variables: DicEonaries (1) • A dic5onary is an associa5ve array or hash table that
contains objects indexed by keys. • Only immutable objects can be used as a key, like
strings, numbers, tuples, etcetera. • You create a dicEonary by enclosing values in curly
braces ('{. . . }'): >>>> a = { … "username" : "xenos", … "home" : "/home/xenos", … "uid" :500 … } >>> a ["uid"] 500
Variables: DicEonaries (2) • Access any value using it's key:
>>> a["username"] "xenos" >>> a["home"] "/home/xenos”
• To insert or modify objects, you assign a value to a key-‐indexed name.
a["username"] = "trixie" a["home"] = "/home/trixie" a["shell"] = "/usr/bin/tcsh”
Variables: DicEonaries (3)
DicEonary membership is tested with the has_key() method: if a.has_key("username"): username = a["username"]
else: username = "unknown user"
This can also be performed more compactly this way. username = a.get("username", "unknown”) user")
Variables: DicEonaries (4)
• To obtain a list of dicEonary keys, use the keys() method.
k = a.keys() k = ["username", "home", "uid", "shell" ]
• Use the del statement to remove an element of a dicEonary.
del a["username"]
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, funcEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented Python 8. DocumentaEon
Flow control
• A block of code contains a list of statements. • Code blocks are denoted by using indenta5on • Flow control can be exerted using looping or condiEonal Statements.
Looping Statements (1)
• Iterates over the members of a sequence, such as a string, list or tuple.
>>>for i in ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ): … print "2 to the power %d is %d” % (i, 2**i)
• Using the range() funcEon you can also give a range: >>> for i in range(1,10):
… print "2 to the power %d is %d” % (i, 2**i)
Looping Statements (2)
• The for statement can iterate over any sequence type and isn't limited to sequences of integers. >>> a = "Hello World” # Print out the characters in a >>> for c in a:
… print c
>>> b = ["Eric", "Trixie", "Coley", "Khamir”]
# Print out the members of a list
>>> for name in b: … print name
Looping Statements (3)
# a = [0,1,2,3,4] # b = [1,2,3,4,5,6,7]
# c = [0,3,6,9,12] # d = [8,7,6,5,4,3,2]
• The range(i, j) funcEon constructs a list of integers with values from i to j à 1.
• If the starEng value is omiUed, it's assumed to be zero.
• An opEonal stride or step size can be given as a third • argument.
a = range(5)
b = range(1,8) c = range(0,14,3)
d = range(8,1,-1)-1)
Play around 2
• Write a short python prog, which iterate through a list and print the iteraEon
• Hint: use enumerate() to iterate through the list
my_list = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(my_list):
print "iteration %i is %s" % (i, name))
Play Around 3
• Write a short prog in python, which prints amount of money you have to pay for a given purchase let say: 1 kg (apples à1.40 euro/kg), 3 kg (banana à1.20 euro/kg)
• Hint: use dicEonary, prices = {'apple': 1.40, 'banana': 1.20} my_purchase = { 'apple': 1, 'banana': 6} grocery_bill = sum( prices[fruit] * my_purchase[fruit] \ for fruit in my_purchase) Print 'I owe the grocer $%.2f' % grocery_bill :
CondiEonal Statements (1)
The if statement: if test: ... elif test: ... else:
...
• The usual comparison operators for tesEng: <, >, ==, !=, <=, >=
• They work on most Python objects
The while statement: while test:
...
CondiEonal Statements (2) • if statement example:
if a == 5: print "It's five!" elif a == 6: print "It's six!" else: print "It's something else.”
• while statement example: a = 0 while a < 3: a = a +1 print "Counting up to 3..."
Play Around 4 • Write a short prog in python which uses the local Eme to print
something ( your acEviEes during the day).
• Hint: import Eme, Eme.localEme(), to get the hours myEme.tm_hour()
import time now = time.localtime() hour = now.tm_hour if hour < 8: print 'sleeping' elif hour < 9: print 'commuting' elif hour < 17: print 'working' elif hour < 18: print 'commuting' elif hour < 20: print 'eating' elif hour < 22: print 'resting' else: print 'sleeping'
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, FuncEons 3. Regular expression 4. File and I/O 5. Packages 6. Object Oriented Python 7. DocumentaEon
FuncEons (1)
• funcEons can be defined using def def fibo(n): # calculate fibonacci up to n ...
• arguments can have default values through assignment in the definiEon def fibo(n=100): # n has default value 100
...
FuncEons (2)
def name(arg1, arg2, ...): """documentaBon""" # opEonal doc string statements return expression # from funcEon
FuncEon (3)
• Return values without a return value a funcEon returns None
• Example def fibo(n): # return Fibonacci series up to n result = []
a, b = 0, 1
while b < n: result.append(b) # see below
a, b = b, a+b
return resultturn result
FuncEon (4)
• Usage – calling the example funcEon without an argument >>> fibo() # call it [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
– calling the example funcEon with an argument >>> fibo(50) # call it again [1, 1, 2, 3, 5, 8, 13, 21, 34]
Play Around 5
• Write a short prog in python which has a funcEon with greets the name given as arguments
def greet(name): print 'hello', name
greet('Jack')
>>> hello, Jack
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, funcEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented Python 8. DocumentaEon
Regular Expressions
• Import the re package to use regular expressions • A number of funcEons are available in re package:
match()
search()
split() sub()
. . .
• For more informaEon see the documentaEon $ pydoc re
Regular Expressions • If we want to write a prog in python, which match a regexp to
validate a list of phone number: import re for test_string in ['555-1212', 'ILLEGAL’]:
if re.match(r'^\d{3}-\d{4}$', test_string): print test_string,'is a valid phone number'
else: print test_string, 'rejected'
Regular Expressions >>> import re >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") >>> m.group(0) # The enEre match 'Isaac Newton' >>> m.group(1) # The first parenthesized subgroup. 'Isaac' >>> m.group(2) # The second parenthesized subgroup. 'Newton' >>> m.group(1, 2) # MulEple arguments give us a tuple. ('Isaac’, ‘Newton’)
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, funcEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented Python 8. DocumentaEon
Reading Files
name = open("filename") – opens the given file for reading, and returns a file object
name.read() - file's entire contents as a string
>>> f = open("hours.txt") >>> f.read() '123 Susan 12.5 8.1 7.6 3.2\n 456 Brad 4.0 11.6 6.5 2.7 12\n 789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
hUp://www.cs.washington.edu/educaEon/courses/cse143/12wi/python.shtml
Line-based File Processing
name.readline() - next line from file as a string
– Returns an empty string if there are no more lines in the file
name.readlines() - file's contents as a list of lines
>>> f = open("hours.txt") >>> f.readline() '123 Susan 12.5 8.1 7.6 3.2\n'
>>> f = open("hours.txt") >>> f.readlines() ['123 Susan 12.5 8.1 7.6 3.2\n', '456 Brad 4.0 11.6 6.5 2.7 12\n', '789 Jenn 8.0 8.0 8.0 8.0 7.5\n']
Writing Files name = open("filename", "w") # write name = open("filename", "a") # append
– opens file for write (deletes any previous contents) , or – opens file for append (new data is placed after previous data)
name.write(str) - writes the given string to the file name.close() - closes file once writing is done
>>> out = open("output.txt", "w") >>> out.write("Hello, world!\n") >>> out.write("How are you?") >>> out.close()
>>> open("output.txt").read() 'Hello, world!\nHow are you?'
hUp://www.cs.washington.edu/educaEon/courses/cse143/12wi/python.shtml
Line-based Input Template
• A file object can be the target of a for ... in loop
• A template for reading files in Python:
for line in open("filename"): statements
>>> for line in open("hours.txt"): ... print(line.strip()) # strip() removes \n 123 Susan 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12 789 Jenn 8.0 8.0 8.0 8.0 7.5
hUp://www.cs.washington.edu/educaEon/courses/cse143/12wi/python.shtml
Play Around 5 • Write a short prog in python, which open all files in you current directory
and prints its content
• Hint: use glob module, – open (filename) to open a file – glob.glob('*.py’) Unix style pathname expansion –
import glob # glob supports Unix style pathname extensions python_files = glob.glob('*.py') for fn in sorted(python_files):
print ' ------', fn for line in open(fn): print ' ' + line.rstrip()
Play Around 6 • Write a short prog in python which sum up integers in
the command line • Hint: important sys module, try: … except ValueError:
import sys
try: total = sum(int(arg) for arg in sys.argv[1:]) print 'sum =', total
except ValueError: print 'Please supply integer arguments'
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, funcEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented python 8. DocumentaEon
Modules (1)
• A module is a file containing Python defini5ons and statements.
• The file name is the module name with the sux .py appended.
• Within a module, the module's name (as a string) is available as the value of the global variable
__name__
Modules (2)
• Example module fibo.py
# Fibonacci numbers module
def fibo(n): # write Fibonacci # series up to n a, b = 0, 1
while b < n: print b a, b = b, a + b
Modules (3) • Import the module with the following command:
>>> import fibo • The funcEons are not included directly • Using the module name you can access the funcEons:
>>> import fibo >>> fibo.fibo(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.__name__ 'fibo'
Modules (4)
• If you intend to use a funcEon oZen you can assign it to a local name:
>>> fib = fibo.fibo >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Modules (5) • The built-‐in funcEon dir() can be used to find out which
names a module defines. It returns a sorted list of strings: >>> import fibo >>> dir(fibo) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', , 'fibo']
• It lists all types of names: variables, modules, func5ons, etc.
• Without arguments, dir() lists the names you have defined currently
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, funcEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented Python 8. DocumentaEon
Packages (1)
• Packages are a way of structuring Python's module • namespace by using doNed module names". • They hide module names from other packages • They are made up of modules
Packages (2) • An example Package:
Sound/ Top-level package __init__.py Initialization formats/ file format conversions/ __init__.py wavread.py ... ...
• __init__.py files are required to make Python treat the directories as containing package
• __init__.py can just be an empty file, but it can also execute iniEalizaEon code for the package.
Packages (3) • Import individual modules from the package:
Import sound.effects.echo – Any func5ons in a package must sEll be referenced by their fully qualified name sound.effects.echo.echofilter( ... )
• An alternaEve way of imporEng the submodule is: From sound.effects import echo – This also loads the submodule echo, and makes it available without its package prex
(Sound.Effects).
echo.echofilter( ... )
• Import all modules from the package: From sound.effects import *
ES: Python
• Today: 1. Python introducEon 2. Basic Python: types, variables, statements, funcEons 3. Regular expression 4. File and I/O 5. Modules 6. Packages 7. Object Oriented Python 8. DocumentaEon
Class • Declare a class by: class <classname>:
– class defini5ons introduce new a namespace, with its OWN scope – all definiEons within a class definiEon are in that new scope
• Use a class: from <classname> import *
– client programs must import the classes they use – client programs used the file name (lowercase), not class name
• classes can be instan5ated into instance objects
from myclass import *!
x = MyClass() # It creates a new instance of the class and assigns this !! ! ! ! ! # object to the local variable x,!! ! ! ! ! # which now represents an instance object.!! ! ! ! ! !!! ! ! ! ! ! ! ! ! ! !
Class Method (Method Objects)
• The first argument of any funcEon within a class is an object reference to a class instance
class MyClass: i = 12345 def f(self): return 'hello world’
• A class constructor is a special method named def __init__(self [, param1, ..., param_n]): …
Class Method (Method Objects)
• Class Methods – The first argument is always the object itself def <methodname>(self, parm1, param2): self.param1 = … self.param2 = … …
• Method objects are instan5a5ons of func5ons in a class.
– the call method object through the instance object x.f()
Class instance (instance object) • You can create/delete aNributes from an instance object (not
from a class object) – create by assignment – delete by using del.
x.counter = 1 # creates a new attribute of!! ! ! ! ! ! ! ! # the instance object x
while x.counter < 10:
x.counter *= 2 print x.counter
del x.counter # delete attribute from the !!! !! !! !! # instance object x
Example of class class BankAccount(object):
def __init__(self, initial_balance=0): self.balance = initial_balance
def deposit(self, amount): self.balance += amount
def withdraw(self, amount): self.balance -= amount
def overdrawn(self): return self.balance < 0
my_account = BankAccount(15) my_account.withdraw(5) print my_account.balance
hUp://wiki.python.org/moin/SimplePrograms
Printing Objects
• By default, Python doesn't know how to print an object:
• We'd like to be able to print a Point object and have its state shown as the output.
>>> p = Point(5, -2) >>> print p <Point instance at 0x00A8A850>
hUp://www.cs.washington.edu/educaEon/courses/cse143/12wi/python.shtml
Printable Objects: __str__
def __str__(self): return string
– converts an object into a string (like Java toString) – invoked automatically when str or print is called def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"
>>> p = Point(5, -2) >>> print p (5, -2) >>> print "The point is " + str(p) + "!" The point is (5, -2)!
hUp://www.cs.washington.edu/educaEon/courses/cse143/12wi/python.shtml
DocumentaEon
• Use the web, there are a lot of websites on python • Check www.python.org for help. • Use the pydoc tool, python manual pages etcetera.
Material for these slides was taken from hUp://www.python.org/doc hUp://www.cs.washington.edu/educaEon/courses/cse143/12wi/python.shtml
Assignment • Create a class python for keeping track of the various hardware
configuraEon and their relaEon to each other as used in our Lab. Note that there are different types of hardware and relaEons.
• So, define a number of types of hardware and a number of types if relaEons (direct cable network, etc) and create a single class that can be instanEated to represent each and every one of them. The instance objects must be connected through relaEons to represent , in the end , the OS3 Lab in an abstract sense. So the objects represent a tree structure represenEng the lab as whole .
• So as an example: your desktop machine has a keyboard a mouse and two screens directly aUached to it. The desktop computer itself is connected to the experimentaEon machines through a network. Then describe the experiment machines etc, etc.
Assignment • The following funcEons must be made available for each node or piece of
hardware
• Print – should print the info of the certain piece only – this includes the hardware descripEon at least. You could only also include it’s
posiEon En the lab/server room, its color etc. • Printall
– Should print he informaEon for this piece and all its descendant – this should traverse the object downwards only
Bonus Thinks of way to create and a actual descripEon of the lab on top of the
abstract descripEon, so; add the name of a computer and who sits behind it etc. this implies that there can be many desktops computer instances that look exactly the same hardware wise, but have different owners.
Assignment
• Further Reading (Discuss/summarize one of the two following talks) – Guido Van Rossum, “Trolls”
• hUp://ontwik.com/python/pycon-‐2012-‐keynote-‐guido-‐van-‐rossum/ , PyCon 2012 Keynote
– Regular expression in Python, Google Python Class Day 2 Part 1 hUp://www.youtube.com/watch?v=kWyoYtvJpe4