Movatterモバイル変換


[0]ホーム

URL:


Uploaded bylbisht2
PPT, PDF10 views

python language programming presentation

python

Embed presentation

Download to read offline
Python ProgrammingD. Sheefa Ruby GraceDepartment of Computer ScienceSarah Tucker College
Uses of Python shell tools system admin tools, command line programs extension-language work rapid prototyping and development language-based modules instead of special-purpose parsers graphical user interfaces database access distributed programming Internet scripting
Basic operations Assignment: size = 40 a = b = c = 3 Numbers integer, float complex numbers: 1j+3, abs(z) Strings 'hello world', 'it's hot' "bye world" continuation via  or use """ long text """"
String operations concatenate with + or neighbors word = 'Help' + x word = 'Help' 'a' subscripting of strings 'Hello'[2]  'l' slice: 'Hello'[1:2]  'el' word[-1]  last character len(word)  5 immutable: cannot assign to subscript
Lists lists can be heterogeneous a = ['spam', 'eggs', 100, 1234, 2*2] Lists can be indexed and sliced: a[0]  spam a[:2]  ['spam', 'eggs'] Lists can be manipulated a[2] = a[2] + 23 a[0:2] = [1,12] a[0:0] = [] len(a)  5
Basic programminga,b = 0, 1# non-zero = truewhile b < 10:# formatted output, without nprint b,# multiple assignmenta,b = b, a+b
Control flow: ifx = int(raw_input("Please enter #:"))if x < 0:x = 0print 'Negative changed to zero'elif x == 0:print 'Zero'elif x == 1:print 'Single'else:print 'More' no case statement
Control flow: fora = ['cat', 'window', 'defenestrate']for x in a:print x, len(x) no arithmetic progression, but range(10)  [0, 1, 2, 3, 4, 5, 6, 7, 8,9] for i in range(len(a)):print i, a[i] do not modify the sequence beingiterated over
Loops: break, continue, else break and continue like C else after loop exhaustionfor n in range(2,10):for x in range(2,n):if n % x == 0:print n, 'equals', x, '*', n/xbreakelse:# loop fell through without finding afactorprint n, 'is prime'
Defining functionsdef fib(n):"""Print a Fibonacci series up to n."""a, b = 0, 1while b < n:print b,a, b = b, a+b>>> fib(2000) First line is docstring first look for variables in local, then global need global to assign global variables
Functions: default argumentvaluesdef ask_ok(prompt, retries=4,complaint='Yes or no, please!'):while 1:ok = raw_input(prompt)if ok in ('y', 'ye', 'yes'): return 1if ok in ('n', 'no'): return 0retries = retries - 1if retries < 0: raise IOError,'refusenik error'print complaint>>> ask_ok('Really?')
Keyword arguments last arguments can be given as keywordsdef parrot(voltage, state='a stiff', action='voom',type='Norwegian blue'):print "-- This parrot wouldn't", action,print "if you put", voltage, "Volts through it."print "Lovely plumage, the ", typeprint "-- It's", state, "!"parrot(1000)parrot(action='VOOOM', voltage=100000)
Lambda forms anonymous functions may not work in older versionsdef make_incrementor(n):return lambda x: x + nf = make_incrementor(42)f(0)f(1)
List methods append(x) extend(L) append all items in list (like Tcl lappend) insert(i,x) remove(x) pop([i]), pop() create stack (FIFO), or queue (LIFO)  pop(0) index(x) return the index for value x
List methods count(x) how many times x appears in list sort() sort items in place reverse() reverse list
Functional programming tools filter(function, sequence)def f(x): return x%2 != 0 and x%3 0filter(f, range(2,25)) map(function, sequence) call function for each item return list of return values reduce(function, sequence) return a single value call binary function on the first two items then on the result and next item iterate
List comprehensions (2.0) Create lists without map(), filter(), lambda = expression followed by for clause + zero or more for orof clauses>>> vec = [2,4,6]>>> [3*x for x in vec][6, 12, 18]>>> [{x: x**2} for x in vec}[{2: 4}, {4: 16}, {6: 36}]
List comprehensions cross products:>>> vec1 = [2,4,6]>>> vec2 = [4,3,-9]>>> [x*y for x in vec1 for y in vec2][8,6,-18, 16,12,-36, 24,18,-54]>>> [x+y for x in vec1 and y in vec2][6,5,-7,8,7,-5,10,9,-3]>>> [vec1[i]*vec2[i] for i inrange(len(vec1))][8,12,-54]
List comprehensions can also use if:>>> [3*x for x in vec if x >3][12, 18]>>> [3*x for x in vec if x <2][]
del – removing list items remove by index, not value remove slices from list (rather than byassigning an empty list)>>> a = [-1,1,66.6,333,333,1234.5]>>> del a[0]>>> a[1,66.6,333,333,1234.5]>>> del a[2:4]>>> a[1,66.6,1234.5]
Tuples and sequences lists, strings, tuples: examples of sequence type tuple = values separated by commas>>> t = 123, 543, 'bar'>>> t[0]123>>> t(123, 543, 'bar')
Tuples Tuples may be nested>>> u = t, (1,2)>>> u((123, 542, 'bar'), (1,2)) kind of like structs, but no elementnames: (x,y) coordinates database records like strings, immutable  can't assign toindividual items
Tuples Empty tuples: ()>>> empty = ()>>> len(empty)0 one item  trailing comma>>> singleton = 'foo',
Tuples sequence unpacking  distribute elements acrossvariables>>> t = 123, 543, 'bar'>>> x, y, z = t>>> x123 packing always creates tuple unpacking works for any sequence
Dictionaries like Tcl or awk associative arrays indexed by keys keys are any immutable type: e.g., tuples but not lists (mutable!) uses 'key: value' notation>>> tel = {'hgs' : 7042, 'lennox': 7018}>>> tel['cs'] = 7000>>> tel
Dictionaries no particular order delete elements with del>>> del tel['foo'] keys() method  unsorted list of keys>>> tel.keys()['cs', 'lennox', 'hgs'] use has_key() to check for existence>>> tel.has_key('foo')0
Conditions can check for sequence membershipwith is and is not:>>> if (4 in vec):... print '4 is' chained comparisons: a less than bAND b equals c:a < b == c and and or are short-circuit operators: evaluated from left to right stop evaluation as soon as outcome clear
Conditions Can assign comparison to variable:>>> s1,s2,s3='', 'foo', 'bar'>>> non_null = s1 or s2 or s3>>> non_nullfoo Unlike C, no assignment within expression
Comparing sequences(1,2,3) < (1,2,4)[1,2,3] < [1,2,4]'ABC' < 'C' < 'Pascal' < 'Python'(1,2,3) == (1.0,2.0,3.0)(1,2) < (1,2,-1)
Modules collection of functions and variables, typically in scripts definitions can be imported file name is module name + .py e.g., create module fibo.pydef fib(n): # write Fib. series up to n...def fib2(n): # return Fib. series up to n
Modules import module:import fibo Use modules via "name space":>>> fibo.fib(1000)>>> fibo.__name__'fibo' can give it a local name:>>> fib = fibo.fib>>> fib(500)
Modules function definition + executablestatements executed only when module is imported modules have private symbol tables avoids name clash for global variables accessible as module.globalname can import into name space:>>> from fibo import fib, fib2>>> fib(500) can import all names defined by module:>>> from fibo import *
Module search path current directory list of directories specified in PYTHONPATHenvironment variable uses installation-default if not defined,e.g., .:/usr/local/lib/python uses sys.path>>> import sys>>> sys.path['', 'C:PROGRA~1Python2.2', 'C:Program FilesPython2.2DLLs', 'C:Program FilesPython2.2lib', 'C:Program FilesPython2.2liblib-tk', 'C:Program FilesPython2.2', 'C:Program FilesPython2.2libsite-packages']
Classes mixture of C++ and Modula-3 multiple base classes derived class can override any methods ofits base class(es) method can call the method of a baseclass with the same name objects have private data C++ terms: all class members are public all member functions are virtual no constructors or destructors (not needed)
Classes classes (and data types) are objects built-in types cannot be used as base classes by user arithmetic operators, subscripting can be redefined forclass instances (like C++, unlike Java)
Class definitionsClass ClassName:<statement-1>...<statement-N> must be executed can be executed conditionally (see Tcl) creates new namespace
Namespaces mapping from name to object: built-in names (abs()) global names in module local names in function invocation attributes = any following a dot z.real, z.imag attributes read-only or writable module attributes are writeable
Namespaces scope = textual region of Python programwhere a namespace is directly accessible(without dot) innermost scope (first) = local names middle scope = current module's global names outermost scope (last) = built-in names assignments always affect innermostscope don't copy, just create name bindings toobjects global indicates name is in global scope
Class objects obj.name references (plus module!):class MyClass:"A simple example class"i = 123def f(self):return 'hello world'>>> MyClass.i123 MyClass.f is method object
Class objects class instantiation:>>> x = MyClass()>>> x.f()'hello world' creates new instance of class note x = MyClass vs. x = MyClass() ___init__() special method forinitialization of objectdef __init__(self,realpart,imagpart):self.r = realpartself.i = imagpart
Instance objects attribute references data attributes (C++/Java data members) created dynamicallyx.counter = 1while x.counter < 10:x.counter = x.counter * 2print x.counterdel x.counter
Method objects Called immediately:x.f() can be referenced:xf = x.fwhile 1:print xf() object is passed as first argument of function  'self' x.f() is equivalent to MyClass.f(x)
InheritanceclassDerivedClassName(BaseClassName)<statement-1>...<statement-N> search class attribute, descending chain of base classes may override methods in the base class call directly viaBaseClassName.method
Multiple inheritanceclassDerivedClass(Base1,Base2,Base3):<statement> depth-first, left-to-right problem: class derived from two classes with a commonbase class
Private variables No real support, but textual replacement (namemangling) __var is replaced by _classname_var prevents only accidental modification, not trueprotection
Exceptions syntax (parsing) errorswhile 1 print 'Hello World'File "<stdin>", line 1while 1 print 'Hello World'^SyntaxError: invalid syntax exceptions run-time errors e.g., ZeroDivisionError, NameError, TypeError
Handling exceptionswhile 1:try:x = int(raw_input("Please enter a number: "))breakexcept ValueError:print "Not a valid number" First, execute try clause if no exception, skip except clause if exception, skip rest of try clause and useexcept clause if no matching exception, attempt outer trystatement
Handling exceptions try.pyimport sysfor arg in sys.argv[1:]:try:f = open(arg, 'r')except IOError:print 'cannot open', argelse:print arg, 'lines:',len(f.readlines())f.close e.g., as python try.py *.py

Recommended

PPTX
Python Workshop - Learn Python the Hard Way
PDF
Introduction To Programming with Python
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
PPTX
An Introduction : Python
PDF
Introduction to Python Programming | InsideAIML
PDF
Introduction to python
PPTX
Python Tutorial Part 1
PDF
Introduction to Python
PPTX
scripting in Python
PPT
python within 50 page .ppt
PPT
python presentation lists,strings,operation
PDF
Python lecture 05
PPTX
Python Workshop
PPT
Python tutorialfeb152012
PPTX
PYTHON PPT.pptx python is very useful for day to day life
PDF
Python Part 1
PPT
Python basics to advanced in on ppt is available
PDF
Python: An introduction A summer workshop
PPT
Pythonintroduction
PPTX
Python programming workshop
PDF
Python cheatsheat.pdf
PPT
Python
PPT
Python Training v2
PPT
python.ppt
PPT
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
PPTX
Introduction to Python Programming
PPT
Python scripting kick off
PDF
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
PDF
ACI 318-2205_American Concrete Institute.pdf
PDF
Albert Pintoy - Specializing In Low-Latency

More Related Content

PPTX
Python Workshop - Learn Python the Hard Way
PDF
Introduction To Programming with Python
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
PPTX
An Introduction : Python
PDF
Introduction to Python Programming | InsideAIML
PDF
Introduction to python
PPTX
Python Tutorial Part 1
PDF
Introduction to Python
Python Workshop - Learn Python the Hard Way
Introduction To Programming with Python
Raspberry Pi - Lecture 5 Python for Raspberry Pi
An Introduction : Python
Introduction to Python Programming | InsideAIML
Introduction to python
Python Tutorial Part 1
Introduction to Python

Similar to python language programming presentation

PPTX
scripting in Python
PPT
python within 50 page .ppt
PPT
python presentation lists,strings,operation
PDF
Python lecture 05
PPTX
Python Workshop
PPT
Python tutorialfeb152012
PPTX
PYTHON PPT.pptx python is very useful for day to day life
PDF
Python Part 1
PPT
Python basics to advanced in on ppt is available
PDF
Python: An introduction A summer workshop
PPT
Pythonintroduction
PPTX
Python programming workshop
PDF
Python cheatsheat.pdf
PPT
Python
PPT
Python Training v2
PPT
python.ppt
PPT
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
PPTX
Introduction to Python Programming
PPT
Python scripting kick off
PDF
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
scripting in Python
python within 50 page .ppt
python presentation lists,strings,operation
Python lecture 05
Python Workshop
Python tutorialfeb152012
PYTHON PPT.pptx python is very useful for day to day life
Python Part 1
Python basics to advanced in on ppt is available
Python: An introduction A summer workshop
Pythonintroduction
Python programming workshop
Python cheatsheat.pdf
Python
Python Training v2
python.ppt
FALLSEM2022-23_ITA3007_ETH_VL2022230100613_Reference_Material_I_23-09-2022_py...
Introduction to Python Programming
Python scripting kick off
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf

Recently uploaded

PDF
ACI 318-2205_American Concrete Institute.pdf
PDF
Albert Pintoy - Specializing In Low-Latency
PPTX
UnrealGameplayAbilitySystemPresentation.pptx
PPTX
MECCA Empire – Hotel Shuttle System for the 2026 FIFA World Cup
 
PPTX
Natural Gas fundamentals and GRU for associated gas trap.pptx
PPTX
How to Select the Right CMMS Software for Your Organization — A Complete Buye...
PPT
new Introduction to PACS.ppt Picture Archieving and communication and medicine
PPTX
علي نفط.pptx هندسة النفط هندسة النفط والغاز
PPTX
TPM Metrics & Measurement: Drive Performance Excellence with TPM | MaintWiz
PDF
Human computer Interface ppt aUNIT 3.pdf
PDF
Narrows Planning Collective Transportation Capstone.pdf
 
PDF
Lecture -06-Hybrid Policies - Chapter 7- Weeks 6-7.pdf
PPTX
Track & Monitor Preventive Maintenance — Best Practices with MaintWiz CMMS
PPTX
Revolutionizing Facilities Management with MaintWiz — AI CMMS for Smart FMaaS
PPTX
How to Implement Kaizen in Your Organization for Continuous Improvement Success
PDF
Handheld_Laser_Welding_Presentation 2.pdf
PPTX
Cloud vs On-Premises CMMS — Which Maintenance Platform Is Better for Your Plant?
PPTX
Vertical turbine pump explains installed in power plants
PDF
Engineering Properties of Agricultural Food Materials-.pdf and ppt
PPTX
Optimizing Operations: Key Elements of a Successful Plant Maintenance Plan — ...
ACI 318-2205_American Concrete Institute.pdf
Albert Pintoy - Specializing In Low-Latency
UnrealGameplayAbilitySystemPresentation.pptx
MECCA Empire – Hotel Shuttle System for the 2026 FIFA World Cup
 
Natural Gas fundamentals and GRU for associated gas trap.pptx
How to Select the Right CMMS Software for Your Organization — A Complete Buye...
new Introduction to PACS.ppt Picture Archieving and communication and medicine
علي نفط.pptx هندسة النفط هندسة النفط والغاز
TPM Metrics & Measurement: Drive Performance Excellence with TPM | MaintWiz
Human computer Interface ppt aUNIT 3.pdf
Narrows Planning Collective Transportation Capstone.pdf
 
Lecture -06-Hybrid Policies - Chapter 7- Weeks 6-7.pdf
Track & Monitor Preventive Maintenance — Best Practices with MaintWiz CMMS
Revolutionizing Facilities Management with MaintWiz — AI CMMS for Smart FMaaS
How to Implement Kaizen in Your Organization for Continuous Improvement Success
Handheld_Laser_Welding_Presentation 2.pdf
Cloud vs On-Premises CMMS — Which Maintenance Platform Is Better for Your Plant?
Vertical turbine pump explains installed in power plants
Engineering Properties of Agricultural Food Materials-.pdf and ppt
Optimizing Operations: Key Elements of a Successful Plant Maintenance Plan — ...

python language programming presentation

  • 1.
    Python ProgrammingD. SheefaRuby GraceDepartment of Computer ScienceSarah Tucker College
  • 2.
    Uses of Pythonshell tools system admin tools, command line programs extension-language work rapid prototyping and development language-based modules instead of special-purpose parsers graphical user interfaces database access distributed programming Internet scripting
  • 3.
    Basic operations Assignment:size = 40 a = b = c = 3 Numbers integer, float complex numbers: 1j+3, abs(z) Strings 'hello world', 'it's hot' "bye world" continuation via or use """ long text """"
  • 4.
    String operations concatenatewith + or neighbors word = 'Help' + x word = 'Help' 'a' subscripting of strings 'Hello'[2]  'l' slice: 'Hello'[1:2]  'el' word[-1]  last character len(word)  5 immutable: cannot assign to subscript
  • 5.
    Lists lists canbe heterogeneous a = ['spam', 'eggs', 100, 1234, 2*2] Lists can be indexed and sliced: a[0]  spam a[:2]  ['spam', 'eggs'] Lists can be manipulated a[2] = a[2] + 23 a[0:2] = [1,12] a[0:0] = [] len(a)  5
  • 6.
    Basic programminga,b =0, 1# non-zero = truewhile b < 10:# formatted output, without nprint b,# multiple assignmenta,b = b, a+b
  • 7.
    Control flow: ifx= int(raw_input("Please enter #:"))if x < 0:x = 0print 'Negative changed to zero'elif x == 0:print 'Zero'elif x == 1:print 'Single'else:print 'More' no case statement
  • 8.
    Control flow: fora= ['cat', 'window', 'defenestrate']for x in a:print x, len(x) no arithmetic progression, but range(10)  [0, 1, 2, 3, 4, 5, 6, 7, 8,9] for i in range(len(a)):print i, a[i] do not modify the sequence beingiterated over
  • 9.
    Loops: break, continue,else break and continue like C else after loop exhaustionfor n in range(2,10):for x in range(2,n):if n % x == 0:print n, 'equals', x, '*', n/xbreakelse:# loop fell through without finding afactorprint n, 'is prime'
  • 10.
    Defining functionsdef fib(n):"""Printa Fibonacci series up to n."""a, b = 0, 1while b < n:print b,a, b = b, a+b>>> fib(2000) First line is docstring first look for variables in local, then global need global to assign global variables
  • 11.
    Functions: default argumentvaluesdefask_ok(prompt, retries=4,complaint='Yes or no, please!'):while 1:ok = raw_input(prompt)if ok in ('y', 'ye', 'yes'): return 1if ok in ('n', 'no'): return 0retries = retries - 1if retries < 0: raise IOError,'refusenik error'print complaint>>> ask_ok('Really?')
  • 12.
    Keyword arguments lastarguments can be given as keywordsdef parrot(voltage, state='a stiff', action='voom',type='Norwegian blue'):print "-- This parrot wouldn't", action,print "if you put", voltage, "Volts through it."print "Lovely plumage, the ", typeprint "-- It's", state, "!"parrot(1000)parrot(action='VOOOM', voltage=100000)
  • 13.
    Lambda forms anonymousfunctions may not work in older versionsdef make_incrementor(n):return lambda x: x + nf = make_incrementor(42)f(0)f(1)
  • 14.
    List methods append(x)extend(L) append all items in list (like Tcl lappend) insert(i,x) remove(x) pop([i]), pop() create stack (FIFO), or queue (LIFO)  pop(0) index(x) return the index for value x
  • 15.
    List methods count(x)how many times x appears in list sort() sort items in place reverse() reverse list
  • 16.
    Functional programming toolsfilter(function, sequence)def f(x): return x%2 != 0 and x%3 0filter(f, range(2,25)) map(function, sequence) call function for each item return list of return values reduce(function, sequence) return a single value call binary function on the first two items then on the result and next item iterate
  • 17.
    List comprehensions (2.0)Create lists without map(), filter(), lambda = expression followed by for clause + zero or more for orof clauses>>> vec = [2,4,6]>>> [3*x for x in vec][6, 12, 18]>>> [{x: x**2} for x in vec}[{2: 4}, {4: 16}, {6: 36}]
  • 18.
    List comprehensions crossproducts:>>> vec1 = [2,4,6]>>> vec2 = [4,3,-9]>>> [x*y for x in vec1 for y in vec2][8,6,-18, 16,12,-36, 24,18,-54]>>> [x+y for x in vec1 and y in vec2][6,5,-7,8,7,-5,10,9,-3]>>> [vec1[i]*vec2[i] for i inrange(len(vec1))][8,12,-54]
  • 19.
    List comprehensions canalso use if:>>> [3*x for x in vec if x >3][12, 18]>>> [3*x for x in vec if x <2][]
  • 20.
    del – removinglist items remove by index, not value remove slices from list (rather than byassigning an empty list)>>> a = [-1,1,66.6,333,333,1234.5]>>> del a[0]>>> a[1,66.6,333,333,1234.5]>>> del a[2:4]>>> a[1,66.6,1234.5]
  • 21.
    Tuples and sequenceslists, strings, tuples: examples of sequence type tuple = values separated by commas>>> t = 123, 543, 'bar'>>> t[0]123>>> t(123, 543, 'bar')
  • 22.
    Tuples Tuples maybe nested>>> u = t, (1,2)>>> u((123, 542, 'bar'), (1,2)) kind of like structs, but no elementnames: (x,y) coordinates database records like strings, immutable  can't assign toindividual items
  • 23.
    Tuples Empty tuples:()>>> empty = ()>>> len(empty)0 one item  trailing comma>>> singleton = 'foo',
  • 24.
    Tuples sequence unpacking distribute elements acrossvariables>>> t = 123, 543, 'bar'>>> x, y, z = t>>> x123 packing always creates tuple unpacking works for any sequence
  • 25.
    Dictionaries like Tclor awk associative arrays indexed by keys keys are any immutable type: e.g., tuples but not lists (mutable!) uses 'key: value' notation>>> tel = {'hgs' : 7042, 'lennox': 7018}>>> tel['cs'] = 7000>>> tel
  • 26.
    Dictionaries no particularorder delete elements with del>>> del tel['foo'] keys() method  unsorted list of keys>>> tel.keys()['cs', 'lennox', 'hgs'] use has_key() to check for existence>>> tel.has_key('foo')0
  • 27.
    Conditions can checkfor sequence membershipwith is and is not:>>> if (4 in vec):... print '4 is' chained comparisons: a less than bAND b equals c:a < b == c and and or are short-circuit operators: evaluated from left to right stop evaluation as soon as outcome clear
  • 28.
    Conditions Can assigncomparison to variable:>>> s1,s2,s3='', 'foo', 'bar'>>> non_null = s1 or s2 or s3>>> non_nullfoo Unlike C, no assignment within expression
  • 29.
    Comparing sequences(1,2,3) <(1,2,4)[1,2,3] < [1,2,4]'ABC' < 'C' < 'Pascal' < 'Python'(1,2,3) == (1.0,2.0,3.0)(1,2) < (1,2,-1)
  • 30.
    Modules collection offunctions and variables, typically in scripts definitions can be imported file name is module name + .py e.g., create module fibo.pydef fib(n): # write Fib. series up to n...def fib2(n): # return Fib. series up to n
  • 31.
    Modules import module:importfibo Use modules via "name space":>>> fibo.fib(1000)>>> fibo.__name__'fibo' can give it a local name:>>> fib = fibo.fib>>> fib(500)
  • 32.
    Modules function definition+ executablestatements executed only when module is imported modules have private symbol tables avoids name clash for global variables accessible as module.globalname can import into name space:>>> from fibo import fib, fib2>>> fib(500) can import all names defined by module:>>> from fibo import *
  • 33.
    Module search pathcurrent directory list of directories specified in PYTHONPATHenvironment variable uses installation-default if not defined,e.g., .:/usr/local/lib/python uses sys.path>>> import sys>>> sys.path['', 'C:PROGRA~1Python2.2', 'C:Program FilesPython2.2DLLs', 'C:Program FilesPython2.2lib', 'C:Program FilesPython2.2liblib-tk', 'C:Program FilesPython2.2', 'C:Program FilesPython2.2libsite-packages']
  • 34.
    Classes mixture ofC++ and Modula-3 multiple base classes derived class can override any methods ofits base class(es) method can call the method of a baseclass with the same name objects have private data C++ terms: all class members are public all member functions are virtual no constructors or destructors (not needed)
  • 35.
    Classes classes (anddata types) are objects built-in types cannot be used as base classes by user arithmetic operators, subscripting can be redefined forclass instances (like C++, unlike Java)
  • 36.
    Class definitionsClass ClassName:<statement-1>...<statement-N>must be executed can be executed conditionally (see Tcl) creates new namespace
  • 37.
    Namespaces mapping fromname to object: built-in names (abs()) global names in module local names in function invocation attributes = any following a dot z.real, z.imag attributes read-only or writable module attributes are writeable
  • 38.
    Namespaces scope =textual region of Python programwhere a namespace is directly accessible(without dot) innermost scope (first) = local names middle scope = current module's global names outermost scope (last) = built-in names assignments always affect innermostscope don't copy, just create name bindings toobjects global indicates name is in global scope
  • 39.
    Class objects obj.namereferences (plus module!):class MyClass:"A simple example class"i = 123def f(self):return 'hello world'>>> MyClass.i123 MyClass.f is method object
  • 40.
    Class objects classinstantiation:>>> x = MyClass()>>> x.f()'hello world' creates new instance of class note x = MyClass vs. x = MyClass() ___init__() special method forinitialization of objectdef __init__(self,realpart,imagpart):self.r = realpartself.i = imagpart
  • 41.
    Instance objects attributereferences data attributes (C++/Java data members) created dynamicallyx.counter = 1while x.counter < 10:x.counter = x.counter * 2print x.counterdel x.counter
  • 42.
    Method objects Calledimmediately:x.f() can be referenced:xf = x.fwhile 1:print xf() object is passed as first argument of function  'self' x.f() is equivalent to MyClass.f(x)
  • 43.
    InheritanceclassDerivedClassName(BaseClassName)<statement-1>...<statement-N> search classattribute, descending chain of base classes may override methods in the base class call directly viaBaseClassName.method
  • 44.
    Multiple inheritanceclassDerivedClass(Base1,Base2,Base3):<statement> depth-first,left-to-right problem: class derived from two classes with a commonbase class
  • 45.
    Private variables Noreal support, but textual replacement (namemangling) __var is replaced by _classname_var prevents only accidental modification, not trueprotection
  • 46.
    Exceptions syntax (parsing)errorswhile 1 print 'Hello World'File "<stdin>", line 1while 1 print 'Hello World'^SyntaxError: invalid syntax exceptions run-time errors e.g., ZeroDivisionError, NameError, TypeError
  • 47.
    Handling exceptionswhile 1:try:x= int(raw_input("Please enter a number: "))breakexcept ValueError:print "Not a valid number" First, execute try clause if no exception, skip except clause if exception, skip rest of try clause and useexcept clause if no matching exception, attempt outer trystatement
  • 48.
    Handling exceptions try.pyimportsysfor arg in sys.argv[1:]:try:f = open(arg, 'r')except IOError:print 'cannot open', argelse:print arg, 'lines:',len(f.readlines())f.close e.g., as python try.py *.py

[8]ページ先頭

©2009-2025 Movatter.jp