Professional Documents
Culture Documents
Python MM PDF
Python MM PDF
Chapter 2................................................................................................................................................. 4
Chapter 3................................................................................................................................................. 6
Chapter 4............................................................................................................................................... 10
Chapter 5............................................................................................................................................... 12
Chapter 6............................................................................................................................................... 17
Chapter 7............................................................................................................................................... 18
Chapter 8............................................................................................................................................... 25
Chapter 9............................................................................................................................................... 26
Chapter 10............................................................................................................................................. 28
Chapter 11............................................................................................................................................. 30
Chapter 12............................................................................................................................................. 33
Chapter 13............................................................................................................................................. 36
Chapter 14............................................................................................................................................. 45
Chapter 15............................................................................................................................................. 46
Chapter 16............................................................................................................................................. 52
Chapter 17............................................................................................................................................. 57
Chapter 18............................................................................................................................................. 63
Chapter 19............................................................................................................................................. 65
Chapter 20............................................................................................................................................. 68
Chapter 21............................................................................................................................................. 75
Chapter 22............................................................................................................................................. 88
Chapter 23............................................................................................................................................. 91
Chapter 24............................................................................................................................................. 97
Chapter 25............................................................................................................................................. 99
Python ကိုေျ ာအရင္ ABC programming language ကေပနစေျ ာအရ ပမမ္္။ ဘာလိုန္႔လဆ
ဲ ိုေတာာ့
python design က ABC အရဲာ့လႊမ္းမိုးမမေတြ ပေပနလိုာ့ျ စ္ ပတမ္္။
Python ကို 1980 ေလာက္မာ concept တစ္ ိုအေပနပနဲာ့ေတာာ့အရေပန ပျ ါ္။ Guido van Rossum
ကအဲာ့ဒါအ ပန္တိုပန္းက CWI မာအရတဲာ့ Amoeba လိုာ့ေ ခတဲာ့ distributed operation system Project
တစ္ ိုမာ လို ္ကိုင္ေပန ပတမ္္။ ABC ပနဲန္႔ေအရးတာ ပ္။ Bill Venners (January 2003) ပနဲာ့
အင္တာဗ းမာ Guido van Rossum က “ ABC ပနဲန္႔ တ္သက္ျ းါ အေတြန္႔အႀကံဳေေတြ
မအရင္းလင္းတာေတြအရတမ္ဗ ္။ ဒပေႀကာင္ာ့ ABC အရဲာ့ ေကာင္းတဲအ
ာ့ က္ေတြကို ABC အရဲာ့ ျ ပနာေတြ
မအရ ဲ အသံိုးျ ဳေပနင္
ို မမ္ာ့ scripting language တစ္ ို ဒါဇင
ို း္ လို ္ န္႔ဆ
ို ိုးံ ျ တ္ ားတမ္္။ စ
ို ေအရးေပနျ ္။ါ
Virtual Machine အရးို အရးို ေလးတစ္ အရ
ို မ္ parser တစ္ အရ
ို မ္ run time တစ္ အရ
ို မ္ လို ္ ားတမ္္။
ABC က
ဲ ကၽြပနေ
္ တာ္ႀကက
ို တ
္ ာ့ဲ အ က္ေတြကို ကၽြပနေ
္ တာာ့ ပနည္း ကၽြပနေ
္ တာာ့ ဟပန္ေအရး ားတမ္္။
syntax အရးို အရးို ေလးေတြသိုးံ တမ္္။ statement ေတြ group န္႔ြဲ န္႔ို တြပနန္႔က
္ င
ြ း္ ေတြ begin-end block
ေတြအစား identation သံိုး ားတမ္ ျ းါ ေတာာ့ data type ေကာင္းတာေလးေတြလို ္ ားတမ္ a
hash table ( or dictionary, as we call it), a list, strings, and numbers.”
ဘာလိုန္႔လဆ
ဲ ိုေတာာ့အမ ားႀကါး ပ ္။သင္အရတာလြမ္တမ္ powerfull ျ စ္တမ္္။ ျ ါးေတာာ့ ေကာ
ေကာင္းမြပန္တဲန္႔ hight-level datastructure ေတြအရတမ္္။ဒပေတြသံိုးျ ါး အရို ္ေ ြးတဲာ့ လို ္ငပန္းေတြကို
c,c++,java တိုန္႔ က္ပနည္းတဲာ့statement ေတြပနဲန္႔ေအရးပနင္တမ္္။ OOP သံိုးအရာမာလည္း java
က္လမ
ြ ္ တမ္္။
အရင္းလင္းျ ါး တ္အရတာလည္းလြမ္တမ္္။ general-purpose high-level programming
language တစ္ ိုလည္းျ စ္တမ္္။ OOP / Imperative/ fuctional style ေတြေအရးလိုန္႔အရတမ္္။
ဘမ္ platform မာ ဲျ စ္ျ စ္ run လိုန္႔အရတဲာ့အတြက္ portable ျ စ္တမ္္။
Guido van Rossum က Python ကို Netherlands က Research Institute for Mathematics
and Computer Science မာ စတင္ ဲာ့ ပတမ္္။ Python ကိုဘာေတြသေဘာက လဲလိုန္႔ Linux
jornal ကေမးျမပန္းအရာမာ “ င္အရားတဲာ့အ က္ကေတာာ့ က ပန
ြ ္ေတာ္programming style
ပနဲာ့အံကိုက္ ဗ
ဲ ္။ interpreter ပနဲာ့ interactive လို ္ေဆာင္ပနိုင္သလို စဆံိုးေအရးျ ါးလည္း ေ ပင္းစ
ေ ပင္းစ ္သံိုးပနိုင္လိုာ့ ေအရးအရတာ ျမပန္တမ္္။ တစ္ျ ားလေတြကလည္း ဒါအ က္က ို productive
ျ စ္ေစတမ္ေျ ာေကတမ္္။
University of Karlsruhe မ Prof. Lutz Prechelt က python ကို တစ္ျ ား language ေတြပနဲာ့
မစ္ျ ပတမ္္။ သန္႔ေျ ာတဲာ့အရလဒ္အက စ္း ်ဴ ္ကေတာာ့္။ “ run time ,memory consumption ,
source text length , comment density , program structure , reliability , လိုအ ္တဲာ့
effort အားလံိုး အမ ်ဴး အစား ၈၀ ေလာက္တည္ေဆာက္ႀကည္ာ့တာ့အ
ဲ ပ. String ေတြdictionary
search ေတြမာ scripting language(perl,python,rexx,tcl) ေတြက conventional language
(c,c++,java)ေတြ က္သာတမ္္။ runtime ပနဲာ့ memory consumption မာ java က္သာျ ါး
c,c++ ေလာက္ေတာာ့မဆိုး ပဘး္။ ေမဘမ ဆိုအရင္ language ေတြႀကားကြာျ ား က္ေတာာ့
သ ္မအရ ပဘး ္။
Python ကို platform အေတာ္မ ားမ ားအတြက္အရပနိုင္ ပတမ္ Linux and Mac OS X
အ ပအ၀င္ေ ပာ့္။ Enviromental setup လို ္ႀကည္ာ့အရေအာင္္။
Getting python
ေပနာက္ဆံိုး က
ြ ္ Python version ေတြ document ေတြဆိုင္အရာအားလံိုးကို
https://www.python.org/ မာ အရပနင္ ပတမ္္။
Installating python
Platform ေတြအမ ားႀကါးမိုန္႔ မမပနဲန္႔ဆိုင္အရာ Platform binary code application ကိုအရမျ ါး Install
ျ ဳေလို ္ေ းအရ ပမမ္္။
Windows Installation
Window အတြက္ဆိုအရင္ေတာာ့
Setting up PATH(optional)
Path variable ကို unix မာ PATH window မာ Path လိုာ့ေ ခ ပတမ္.(Unix က case sensitive
window ကေတာာ့ case insensitive)
Running Python
Interactive Interpreter
Command line မ
ဲ ာ python လိုန္႔အရိုက္ျ ါး enter ႏွာ ္ ပ္။ ဒပဆို စေအရးလန္႔အရ
ို ပျ ါ္။
Macintosh − The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.
Python interpreter သံိုး ိုန္႔ဆိုအရင္ command prompt မာ python လိုန္႔ enter ႏွာ ္အရင္အရ ပျ ါ္။
C:\Users\minthargyi>PYTHON
>>> float(12) / 7
1.7142857142857142
>>>
မမႏွာစ္သက္အရာ editor ပနဲန္႔ print “hello world” ေလးေအရး helloworld.py လိုန္႔ desktop
ေ ခမာသမ္း ေ း ပ အဓကကေတာာ့ .py extension ျ စ္အရမာျ စ္ျ ါး မမသမ္းဆည္း ားအရာေပနအရာကို
သအရအရမာျ စ္ ပတမ္္။
C:\Users\minthargyi>cd Desktop
C:\Users\minthargyi\Desktop>python helloworld.py
hello world
C:\Users\minthargyi\Desktop>
Python Internals
Python ကို interpreted programming သိုန္႔ scripting language လိုန္႔ေျ ာႀက ပလမ္ာ့မမ္္။ အမပန္
တာာ့ Python က interpreted ျ စ္သလို compiled language လည္းျ စ္ ပတမ္္။ ဒပေ မမ္ာ့
compiled language လိုေျ ာအရင္ပနားလည္းမမလဲပန
ြ ိုင္ ပေသးတမ္္။ compiler က python code ကို
machine language ေျ ာင္းလိုက္တမ္လိုန္႔ျမင္ႀက ပလမ္ာ့မမ္္။ python code ကို intermediate
code အအရင္ေျ ာင္း ပတမ္္။ အဲာ့ဒပကိုမ PVM လိုာ့ေ ခတဲာ့ python virtual machine မာ execute
လို ္ ပတမ္္။ java ပနဲာ့တ ပတမ္္။ python ကို Jpython သံိုးျ ါး java byte code အျ စ္ေျ ာင္း
လိုန္႔အရတဲာ့ပနည္းေတြေတာင္ အရ ပတမ္္။
ဘမ္လို လ
ဲ ို ္လို ္ “helloworld.pyc” ဆိုတဲာ့ file ေလးလို ္ေ း ပလမ္ာ့မမ္္။
Directory တစ္ ို ဲမာ အရေပနတဲာ့ python file အားလံိုးကို compile လို ္ င္လည္းအရ ပတမ္္။
python -m compileall .
ဒပေ မမ္ာ့ေျ ာ ဲာ့သလို ဲ user ကလို ္စအရာမလို ပဘး္။ python program file အရတဲာ့ directory မာ
write access အရအရင္ .pyc file ေတြသမ္းတတ္ ပတမ္္။ write access မအရလည္း အလို ္လို ္ေပနမာ
ပ ဲ ္။ byte code ို ္ျ ါး program အရ ္သာြ းအရင္ က္လိုက္မာ ပ္။ python program ကို execute
လို ္တိုင္း .pyc file အရလားအအရင္ႀကည္ာ့ ပတမ္္။ ိုျမပန္တာ့အ
ဲ တြက္ အဲာ့ဒါ file ကို load လို ္ေ းမာ ပ္။
မအရဘးဆိုအရင္ေတာာ့ byte code ို ္ျ ါး execute လို ္ ပတမ္္။ Execute လို ္တမ္ဆိုတာ byte
code ေတြကို Python Virtual Machine (PVM) ေ ခမာ run တာကိုဆိုလိုတာျ စ္ ပတမ္္။
Python script execution လို ္တိုင္း byte code ိုတ္တမ္္။ module အေပနပနဲာ့သံိုးအရင္လည္း
သက္ဆိုင္အရာ .pyc file မ
ဲ ာသမ္း ားတမ္္။
C:\Users\minthargyi>cd Desktop
C:\Users\minthargyi\Desktop>dir
Directory of C:\Users\minthargyi\Desktop
C:\Users\minthargyi\Desktop>
C:\Users\minthargyi\Desktop>python helloworld.py
hello world
C:\Users\minthargyi\Desktop>dir
Directory of C:\Users\minthargyi\Desktop
ေပနာက္တစ္ပနည္းသြားႀကည္ာ့မမ္္။
C:\Users\minthargyi\Desktop>python
hello world
>>> exit()
C:\Users\minthargyi\Desktop>dir
Directory of C:\Users\minthargyi\Desktop
C:\Users\minthargyi\Desktop>
Interpreter
Programming language တစ္ ို ိုပနဲာ့ေအရး ားတဲာ့ instruction ေတြကို execute လို ္ ပတမ္္။
ိုေကာင္းတဲာ့ language တစ္ ိုအျ စ္ေျ ာင္းလဲျ ါးမ execute လို ္တာလည္းျ စ္ပနိုင္ ပတမ္္။
Help
help("execfile")
Programmng language ေတာ္ေတာ္မ ားမ ားမာ statement ေတြ group ြန္႔ဲ ိုာ့ character ေတြ
keyword ေတြသံိုးႀက ပတမ္္။
Eg
First block
Inerblock statement 1
Inerblock statement 2
Inerblock statement 3
Second block
Third block
Variables
Variable ကို တပန္ ိုးေတြ သမ္း ား ိုာ့ ေပနအရာလြတ္ေလးေတြ container ေလးေတြလိုာ့ မတ္သားပနိုင္
ပတမ္္။ program run ေပန ပန္မာ တပန္ ိုးေတြအရမသံိုးစြပန
ဲ ိုင္သလို
တပန္ ိုးအသစ္ေတြ ေျ ာင္းလဲ ည္ာ့သြင္းပနိုင္ ပတမ္္။
Python မာ ေတာာ့ variable declaration လို ္ ိုန္႔မလို ပဘး ္။ မမလိုတဲာ့အ ပန္ သံိုးအရိုံ ပ ဲ္။
ေပနာက္တစ္ က္က variable value ေျ ာင္းပနိုင္သလို variable data type ကိုလည္း program
run ေပန ပန္မာ ေျ ာင္းပနိုင္ ပတမ္္။ integer variable တစ္ ိုလို ္သံိုးေပနာက္လိုလာအရင္ ၎ကို
variable ကို string type အျ စ္ေျ ာင္းလဲသံိုးပနိုင္ ပတမ္္။ Eg.
>>> i=42
>>> i=i+1
>>> print i
43
>>>
Variable ပနဲန္႔ identifier တတမ္လိုန္႔မားေျ ာႀက ပတမ္္။ အရင္းအရင္းေျ ာအရအရင္ variable အရဲန္႔ပနာမည္ ကို
identifier လိုန္႔ေ ခ ပတမ္္။ ဒပေ မမ္ာ့ variable ကအဲာ့ဒါ က္ ို ပတမ္္။ variable မာ
ပနာမည္အရမမ္္။ type အရမမ္္။ scope အရမမ္ value ေတြအရမမ္္။ ျ ါးေတာာ့ identifier ဆိုတာ
variable name အတြက္ မမဟိုတ္ ပဘး္။ အျ ား variables, types, labels, subroutines or
functions, packages စတာ ေတြအတြက္လည္းသံိုး ပေသးတမ္္။
Python Keywords
and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for,
from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while,
with, yield
>>> i=42
>>> i=42+0.11
>>> i="forty"
>>>
Identify function id() ပနဲန္႔ေသ ာေအာင္လို ္ႀကည္ာ့မမ္္။ instance (Object /variable )အားလံိုး
မာ identity အရ ပတမ္္။
>>> x = 3
>>> print id(x)
157379912
>>> y = x
>>> print id(y)
157379912
>>> y = 2
>>> print id(y)
157379924
>>> print id(x)
157379912
>>>
Numbers
Python အရဲာ့ built in data type ေတြကို object type လိုန္႔လည္းေ ခ ပေသးတမ္္။ number
အတြက္ 4 မ ဳေးအရ ပတမ္္။
Integer
Normal integers
e.g. 4321
Octal literals (base 8)
A number prefixed by a 0 (zero) will be interpreted as an octal number
example:
Strings
ေပနာက္ဆံိုးစာလံိုးကေတာာ့
>>> s[len(s)-1]
's'
ိုလမ
ြ ္တဲန္႔ပနည္းလမ္းက ေပနာက္ဆံိုး character ကို index -1 ဒိုတမကို -2 သံိုးပနိုင္ ပတမ္္။
>>> s[-1]
's'
>>> s[-2]
'r'
Python မာ character type မအရ ပဘး ၊ string size one ဆို character ပ ဲ
Concatenation
Strings can be glued together (concatenated) with the + operator:
"Hello" + "World" will result in "HelloWorld"
Repetition
String can be repeated or repeatedly concatenated with the asterisk operator "*":
"*-*" * 3 -> "*-**-**-*"
Indexing
"Python"[0] will result in "P"
Slicing
Substrings can be created with the slice or slicing notation, i.e. two indices in
square brackets separated by a colon:
"Python"[2:4] will result in "th"
Size
len("Python") will result in 6
Java ပနဲာ့တျ ါး C C++ ပနဲာ့မတတာက python string ေတြကို ေျ ာင္းလိုန္႔မအရ ပဘး္။ index postion
ေတြကို value ေျ ာင္းႀကည္ာ့အရင္ error ေ း ပလမ္ာ့မမ္္။
>>> s = "Some things are immutable!"
>>> s[-1] = "."
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
A String Peculiarity
String ေတြမာ းျ ား က္တစ္ ိုအရတမ္္။ eg/ “is” operator လို ပမမ္္။ a ပနဲန္႔ b က string
ေတြျ စ္တမ္ “a is b ” ဆိုအရင္ identity တမတစစ္တာျ စ္ ပတမ္(memory share
သံိုးႀကတမ္ေ ပာ့ )္။ “a is b” က True ဆိုအရင္ “a==b” လည္းတအရမာျ စ္ ပတမ္္။ ဒပေ မမ္ာ့
“a==b” ျ စ္မံိုပနာ့ေ
ဲ တာာ့ “a is b” က True မျ စ္ ပဘး္။ eg
>>> a = "Linux"
>>> b = "Linux"
>>> a is b
True
String အအရည္ဆိုအရင္ေအရာ ?
>>> a = "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
>>> b = "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
>>> a is b
True
အတတ ပ ဲ ိုျ မမ္ာ့ eg မာေတာာ့ မတေတာာ့ ပဘး
>>> a = "Baden-Württemberg"
>>> b = "Baden-Württemberg"
>>> a is b
False
>>> a == b
True
Special character hypen ပေပနလိုာ့ျ စ္ ပတမ္္။
>>> a = "Baden!"
>>> b = "Baden!"
>>> a is b
False
>>> a = "Baden1"
>>> b = "Baden1"
>>> a is b
True
\newline Ignored
\\ Backslash (\)
Operators
Input Function
Python မာ keyboard ကေပန input မ ိုန္႔ input() function ပ ပတမ္္။ optional parameter
တစ္ ို ပျ ါးေတာာ့ prompt string ေလးတစ္ ိုျ ိုန္႔သံိုးပနိုင္ ပတမ္္။
Input function ကို ေ ခတဲာ့အ ပ program flow က user input မေ းမ င္းအရ ္ေပနမာ ပ္။
optional parameter ဲက string ကေတာာ့ screen မာေ ခေပနမာ ပ္။
ျ ါးေတာာ့ user input လို ္သမ ကို interpret လည္းလို ္မာ ပ္။ integer ဆိုအရင္ Integer ၊ list
ည္န္႔ အရင္ list return ျ ပန္ေ း ပတမ္္။
name = input("What's your name? ")
print("Nice to meet you " + name + "!")
age = input("Your age? ")
print("So, you are already " + str(age) + " years old, " + name + "!")
“input_test.py” လိုန္႔သမ္းျ ါး runႀကည္ာ့ ပ္။
$ python input_test.py
What's your name? "Frank"
Nice to meet you Frank!
Your age? 30
So, you are already 30 years old, Frank!
တကမ္လိုန္႔ ကိုက name ညာ့္အရာမာ quotes ေတြက ပန္သြားအရင္ေတာာ့ error ျ ပလမ္ာ့မမ္္။
Traceback (most recent call last):
File "input_test.py", line 1, in <module>
name = input("What's your name? ")
File "<string>", line 1, in <module>
NameError: name 'Frank' is not defined
အစမာေျ ာ ဲာ့သလို ဲ input ကို interpret လို ္တဲာ့အတြက္ ေႀကာင္ာ့ quoutes မ ပအရင္ variable
အေပနပနဲာ့သတ္မတ္တာ့အ
ဲ တြက္ေႀကာင္ာ့ error ျ တာျ စ္ ပတမ္္။
>>> name = input("What's your name? ")
What's your name? "John"
>>>
>>> age = input("Your age? ")
Your age? 38
>>> print(age, type(age))
(38, <type 'int'>)
>>> colours = input("Your favourite colours? ")
Your favourite colours? ["red","green","blue"]
>>> print(colours)
['red', 'green', 'blue']
>>> print(colours, type(colours))
(['red', 'green', 'blue'], <type 'list'>)
>>>
Input with raw_input()
Condition ေတြစစ္တာ့အ
ဲ ပ variable ေတြ ကို comparison and arithmetic expression ေတြပနဲာ့
တြဲသံိုးႀက ပတမ္္။ ဒါ expression ေတြကို Boolean value ေတြျ စ္တာ့ဲ True or False
လားတြက္ က္ ပတမ္္။ decision လို ္ ိုန္႔ေအရးသားတဲာ့ statement ေတြကို condition statement
or conditional expressions or conditional constructs လိုန္႔ေ ခ ပတမ္္။
The if Statement
မ ိုလိုေအရး ပတမ္
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
condtion 1 မပန္ အရင္ statement_block_1 မမပန္ အရင္ condition 2 ္စစ္ မပန္အရင္
statement_block_2 မားအရင္ statement_block_3 အလို ္လို ္ ပမမ္္။
Abbreviated IF statement
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i + 1
standard input
standard output
standard error
sys.stdin
sys.stdout
sys.stderror
ေအာက္ ပ example မာ keyboard input ကို while loop သံိုး တ္ျ ား ပတမ္္။ယ္။၏
import sys
text = ""
while 1:
c = sys.stdin.read(1)
text = text + c
if c == '\n':
While loop တစ္ ိုဟာ သသတ္မတ္ ားတဲာ့ အေျ အေပနတစ္ ိုေအရာက္မ အဆံိုးသတ္ ပတမ္္။
break statement ပနဲာ့ဆိုလ င္ သတ္မတ္ က္မျ ည္ာ့မါလည္း loop ကေပန က
ြ ္သြားေအာင္ လို ္လိုာ့
အရ ပတမ္္။ break ပနဲာ့ continue ကလည္းမတ ပဘး္။ continue ကလက္အရ loop ကိုအရ ္ျ း loop
ေပနာက္တစ္ဆင္ာ့ကိုကး ပတမ္္။
Introduction
For loop statement ကလည္း C C++ ပနဲန္႔ကြဲ ပတမ္္။ batsh shell loop ပနဲန္႔ဆင္ ပတမ္္။
တစ္ ပတစ္အရံ list ေတြ number အမ ားႀကါးေတြပနဲာ့ operation ေတြလို ္အရတာအရ ပတမ္္။ python
for statement က ဒါလို list ေတြ range type ေတြအမ ားႀကါးအတြက္ အဆင္ေျ ပတမ္္။
List ေတြကို interation လို ္အရင္ list ကို loop body မာ ေျ ာင္းလဲတာေတြမလို ္တာေကာင္း
ပတမ္္။ eg.
အဲာ့လိုမျ စ္ေအာင္ slicing operator သံိုးျ ါး list ကို copy ြားျ ါးသံိုးပနိုင္ ပတမ္္။
colours = ["red"]
for i in colours[:]:
if i == "red":
colours += ["black"]
if i == "black":
colours += ["white"]
print colours
ဒါတစ္ ပ print ိုတ္မာက
['red', 'black']
“colours” list ကိုေျ ာင္းေ မမ္ာ့လည္း loop က element ကမေျ ာင္းတဲာ့အတြက္ လို င္တဲာ့
result က
ြ ္ ပတမ္္။
Python မာ လလ print လို ္ ိုန္႔ပနည္းလမ္းေတြအမ ားႀကါးအရ ပတမ္္။ string class အရဲာ့ format
method ကိုေတာာ့သံိုးသင္ာ့ ပတမ္္။
%[flags][width][.precision]type
Eg ေအရးျ ားတဲာ့ဆါမာ ဒိုတမ “%8.2f” က float number အတြက္ ပ္။ တစ္ျ ား place holder
ေတြလို ဲ % ပနဲာ့စ ပတမ္္။ ေပနာက္မာက string မာ ပမမ္ာ့ digit အေအရအတြက္ .
ေပနာက္မာ ပတာကေတာာ့ float point ေပနာက္က number အေအရအတြက္ျ စ္ ပတမ္္။ f ကေတာာ့
place holder သည္ float ျ စ္ေႀကာင္းေျ ာ ပတမ္္။
“%5d” ကေတာာ့ content tuple ဲက 453 အတြက္ ပ္။ character 5 လံိုးပနဲာ့အရိုက္ ပမမ္္။ 453 က
3 လံိုး ဲ ပေတာာ့ ေအရာ့မာ black 2 လံိုး ပ ပမမ္္။
Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Obsolete and equivalent to 'd', i.e. signed integer decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
Examples
>>> print("%10.3e"% (356.08977))
3.561e+02
>>> print("%10.3E"% (356.08977))
3.561E+02
>>> print("%10o"% (25))
31
>>> print("%10.3o"% (25))
031
>>> print("%10.5o"% (25))
00031
>>> print("%5x"% (47))
2f
>>> print("%5.4x"% (47))
002f
>>> print("%5.4X"% (47))
002F
>>> print("Only one percentage sign: %% " % ())
Only one percentage sign: %
>>>
Flag Meaning
# Used with o, x or X specifiers the value is preceded with 0, 0o, 0O, 0x or 0X
respectively.
0 The conversion result will be zero padded for numeric values.
- The converted value is left adjusted
If no sign (minus sign e.g.) is going to be written, a blank space is inserted before the
value.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).
Examples:
>>> print("%#5X"% (47))
0X2F
>>> print("%5X"% (47))
2F
>>> print("%#5.4X"% (47))
0X002F
>>> print("%#5o"% (25))
0o31
>>> print("%+d"% (42))
+42
>>> print("% d"% (42))
42
>>> print("%+2d"% (42))
+42
template ဆိုတာက format codes ေတြ ပတဲာ့ string ျ စ္ျ ါးေတာာ့ text
ေတြ မ
ဲ ာ ည္ာ့ ားမာ ျ စ္ ပတမ္္။ အစား ိုးမမ္ာ့ စာေတြကိုေတာာ့ {} မ
ဲ ာ ည္ာ့ ား ပတမ္္။
{} ပနဲန္႔ အတ အ မ
ဲ ာ အရတဲာ့ code ေတြကို formatted value အရတဲာ့ arugument ပနဲန္႔
အစား ိုးမာျ စ္ ပတမ္္။ {} မ
ဲ မ ပတာေတြကေတာာ့ ံိုမပန္ စာေႀကာငး္လို ဲ ေျ ာင္းလဲမိုမအရ print
လို ္ ပမမ္္။ {} ေတြ print လို ္ ိုန္႔ လိုလာအရင္ေတာာ့ 2 ိုေအရးျ ါး escape လို ္ေ းအရ ပမမ္ {{ ပနဲာ့ }}
.format method အတြက္ argument ႏွာစ္မ ဳေးအရ ပတမ္္။ 0 ကေပနစတဲာ့ positional arugment list
(p0,p1,….) အဲန္႔ေပနာက္မာ keyword argument ေတြက name=value ံိုစံပနဲာ့အရ ပမမ္္။
.format() method အရဲာ့ Positional parameter ေတြကို လို င္အရင္ eg.{0} {1}စသျ င္ာ့ အသံိုးျ ဳေ
ပနိုင္ ပတမ္္။ string modulo operator % မာလို ဲ index ေပနာက္မာ : ံျ ါး format string ေတြ
ည္ာ့ပနိုင္ ပေသးတမ္္။ eg {0:5d}
Option Meaning
'<'
The field will be left-aligned within the available space. This is usually the default
for strings.
'>'
The field will be right-aligned within the available space. This is the default for
numbers.
If the width field is preceded by a zero ('0') character, sign-aware zero-padding for
numeric types will be enabled.
>>> x = 378
'0' >>> print("The value is {:06d}".format(x))
The value is 000378
>>> x = -378
>>> print("The value is {:06d}".format(x))
The value is -00378
Forces the padding to be placed after the sign (if any) but before the digits. This is
'=' used for printing fields in the form "+000000120". This alignment option is only
valid for numeric types.
'^' Forces the field to be centered within the available space.
Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-'
indicates that a sign should be used only for negative numbers, which is the default
behavior.
indicates that a leading space should be used on positive numbers, and a minus sign
space
on negative numbers.
result က
Countries and their capitals:
United States: Washington
Canada: Ottawa
Austria: Vienna
Netherlands: Amsterdam
Germany: Berlin
UK: London
Switzerland: Bern
England: London
US: Washington
France: Paris
enter(...):
S.center(width[, fillchar]) -> str
Return S centred in a string of length width. Padding is done using the specified fill
character. The default value is a space.
Examples:
>>> s = "Python"
>>> s.center(10)
' Python '
>>> s.center(10,"*")
'**Python**'
ljust(...):
S.ljust(width[, fillchar]) -> str
Return S left-justified in a string of length "width". Padding is done using the
specified fill character. If none is given, a space will be used as default.
Examples:
>>> s = "Training"
>>> s.ljust(12)
'Training '
>>> s.ljust(12,":")
'Training::::'
>>>
rjust(...):
S.rjust(width[, fillchar]) -> str
Return S right-justified in a string of length width. Padding is done using the
specified fill character. The default value is again a space.
Examples:
>>> s = "Programming"
>>> s.rjust(15)
' Programming'
>>> s.rjust(15, "~")
'~~~~Programming'
>>>
zfill(...):
S.zfill(width) -> str
Examples:
>>> account_number = "43447879"
>>> account_number.zfill(12)
'000043447879'
>>> # can be emulated with rjust:
...
>>> account_number.rjust(12,"0")
'000043447879'
>>>
Python 3.6 မာ formatted string leterals မ ား ပလာ ပတမ္္။ ‘f’ ပနဲန္႔စ ပတမ္္။ str.format()
ကလက္ ံ တဲာ့ formatting syntax ပနဲန္႔တ ပတမ္္။ format method အရဲာ့ format string လို ဲ {} ပနဲန္႔
အစား ိုးမမ္ာ့ေပနအရာေတြ ပတမ္္။ eg.
>>> price = 11.23
>>> f"Price in Euro: {price}"
'Price in Euro: 11.23'
>>> f"Price in Swiss Franks: {price * 1.086}"
'Price in Swiss Franks: 12.195780000000001'
>>> f"Price in Swiss Franks: {price * 1.086:5.2f}"
'Price in Swiss Franks: 12.20'
>>> for article in ["bread", "butter", "tea"]:
... print(f"{article:>10}:")
...
bread:
butter:
tea:
Import လို ္ေ းတာက python 3 အတြက္လည္း အဆင္ေျ ေစတာေႀကာင္ာ့ လို ္သင္ာ့ ပတမ္္။
Strings
String ေတြ character အတြဲလိုက္ေတြအေပနပနဲာ့ျမင္ပနိုင္ ပတမ္္။အမ ဳေးမ ဳေးေ ာ္ျ ပနိုင္ ပတမ္္။
Indexing strings
“Hello World” ဆိုတဲာ့ string တစ္ ိုမာ character ေတြကို ဘမ္မညာသိုန္႔ 0 ကေပနစျ ါး
enumeration လို ္ ပတမ္္။ ညာဘက္ကေပနဆိုအရင္ -1 ကစ ပတမ္္။
String ဲက character တစ္ ိုျ င္းဆါကို string name ပနဲာ့ [index no] သံိုးျ ါး အသံ
အသံိုးျ ဳေ ပနိုင္ ပတမ္္။
>>> txt[-1]
'd'
>>> txt[-5]
'W'
Python Lists
Pythonမာ list ကေတာာ့ versatile data type တစ္ျ စ္ ပတမ္။ versatile ဆိုတာကေတာာ့ type
အမ ဳေးေျ ာင္းလဲအသံိုးျ ဳေပနင
ို ္တာျ စ္ ပတမ္္။eg. integer list , string list. List ေတြေအရးတဲာ့အ ပ [
[] ဲမာ comma sepatater value(CSV) အေပနပနဲန္႔ေအရးပနိုင္ ပတမ္္။ c,c++,java တန္႔ဆ
ို ါက array
ပနဲာ့တေ မဲာ့ ံိုမပန္ classical array ေတြ က္ ိုျ ါး flexible ျ စ္ ပတမ္္။ စ မာ list ဲက item
ေတြက type မတလည္းအရ ပတမ္္။ ျ ါးေတာာ့ list size က ္ ာ့လ
ဲ ိုန္႔အရ ပတမ္္။ array မာလို
အေသမဟိုတ္ ပဘး္။
An example of a list:
list itemေတြကို သံိုးစြဲ ိုန္႔(access)လို ္ ိုန္႔ ပနည္းအမ ဳေးမ ဳေးအရ ပတမ္္။ အလြမ္ဆံိုးကေတာာ့ index
သံိုးတာ ပ္။
>>> languages = ["Python", "C", "C++", "Java", "Perl"]
>>> languages[0]
'Python'
>>> languages[1]
'C'
>>> languages[2]
'C++'
>>> languages[3]
'Java'
ိုျ ားတဲာ့ဆါမာ data type တ ပတမ္္။ မတလဲအရ ပတမ္္။
group = ["Bob", 23, "George", 72, "Myriam", 29]
Sublists
List မ
ဲ ာ sublist ေတြအရပနိုင္ ပတမ္္။ sublist မ
ဲ ာ sublist အရပနိုင္ ပေသးတမ္္။
>>> person = [["Marc","Mayer"],["17, Oxford Str", "12345","London"],"07876-
7876"]
>>> name = person[0]
>>> print name
['Marc', 'Mayer']
>>> first_name = person[0][0]
>>> print first_name
Marc
>>> last_name = person[0][1]
>>> print last_name
Mayer
>>> address = person[1]
>>> street = person[1][0]
>>> print street
17, Oxford Str
Tuples
Generalization
List ေတြ string ေတြမာ common properties ေတြအရ ပတမ္္။ eg.list item ေတြ string
character ေတြကို အစစ္လိုက္အရျ ါးေတာာ့ Index ပနဲာ့အသံိုးျ ဳေပနိုင္ ပတမ္္။ tuple လိုတစ္ျ ား data
type ေတြအရ ပေသးတမ္္။(buffer and xrange) "sequence data types" or "sequential data
types"လိုန္႔ေ ခ ပတမ္္။
"sequence data types" အတြက္ operator ေတြ method ေတြကေတာာ့ အတတ ပ ဲ္။
Slicing
String က
ဲ တစ္စတ္တစ္ ိုင္း , list ဲက တစ္စတ္တစ္ ိုင္း လို င္အရင္ slice operator
သံိုး ပတမ္္။ range တစ္ ိုပနဲာ့ မတဲာ့သေဘာ ပ ဲ ္။ eg
>>> str = "Python is great"
>>> first_six = str[0:6]
>>> first_six
'Python'
>>> starting_at_five = str[5:]
>>> starting_at_five
'n is great'
>>> a_copy = str[:]
>>> without_last_five = str[0:-5]
>>> without_last_five
'Python is '
>>>
Length
Sequence အရဲာ့ length ကိုေျ ာတာ ပ္။ list, string , tuple ေတြအရဲာ့ length ကို len()
သံိုးျ ါးသပနင္ ပတမ္္။ string မာဆိုအရင္ character ေတြကိုေအရတြက္ျ ါးေတာာ့ list,tuple
ေတြမာေတာာ့ element ေတြကိုေအရတြက္ ပတမ္္။ sublist ေတြကို 1 element
အေပနပနဲန္႔ေအရတြက္ ပတမ္္။
>>> txt = "Hello World"
>>> len(txt)
11
>>> a = ["Swen", 45, 3.54, "Basel"]
>>> len(a)
4
Concatenation of Sequences
Sequences ေတြကိုေ ပင္းစ ္တာ ဟာ ဂဏပန္း ႏွာစ္လံိုးေ ပင္းသလို ပ ဲ္။ operator sign
လည္းတ ပတမ္္။
>>> firstname = "Homer"
>>> surname = "Simpson"
>>> name = firstname + " " + surname
>>> print name
Homer Simpson
>>>
List အတြက္လည္းအတတ ပ ဲ
>>> colours1 = ["red", "green","blue"]
>>> colours2 = ["black", "white"]
>>> colours = colours1 + colours2
Repetitions
Further examples:
>>> 3 * "xyz-"
'xyz-xyz-xyz-'
List ေတြအေႀကာင္းျ ါးေတာာ့ dictionary ေတြအေႀကာင္း ပ္။ Dictionary က list လို ဲ runtime မာ
ေျ ာင္းလဲတာေတြလို ္ပနိုင္ ပတမ္္။ list မ
ဲ ာ dictionary အရပနိုင္သလို dictionary မ
ဲ ာ လညး္ list
ေတြ ပ၀င္ပနိုင္ ပတမ္္။ကြာျ ား က္က list ေတြက ordered sets ေတြျ စ္ျ ါးေတာာ့ dictionary
ေတြကေတာာ့ unordered sets ေတြျ စ္ ပတမ္္။ ျ ါးေတာာ့ dictionary ေတြမာ item ေတြကို
position ပနဲာ့မဟိုတ္ ဲ key ပနဲန္႔ access လို ္တာျ စ္ ပတမ္္။Associative array (hashes)
လိုန္႔လည္းေ ခ ပတမ္္။ dictionary မာ key ပနဲန္႔ value ကိုmapping ား ပတမ္္။ dicationay
value က python data type ႀကက္တာျ စ္ပနိုင္ ပတမ္္။ dictionary ေတြက unordered key-
value-pairs ေတြျ စ္ ပတမ္္။
Dictionary ေတြက string , list , tuple ေတြလို sequence operation လို ္မအရ ပဘး ္။
Examples of Dictionaries
Dictionary အလြတ္တစ္ ို
>>> empty = {}
>>> empty
{}
Eg continue
>>> food = {"ham" : "yes", "egg" : "yes", "spam" : "no" }
>>> food
{'egg': 'yes', 'ham': 'yes', 'spam': 'no'}
>>> food["spam"] = "yes"
>>> food
{'egg': 'yes', 'ham': 'yes', 'spam': 'yes'}
>>>
German-English dictionary:
# -*- coding: iso-8859-1 -*-
German-french
# -*- coding: iso-8859-1 -*-
More
# -*- coding: iso-8859-1 -*-
Operators on Dictionaries
Operator Explanation
len(d) returns the number of stored entries, i.e. the number of (key,value) pairs.
del d[k] deletes the key k together with his value
k in d True, if a key k exists in the dictionary d
k not in d True, if a key k doesn't exist in the dictionary d
Dictionary ေတြကိုေ ပင္းစ ္ပနိုင္ ပတမ္္။ key တတာေတြ ပအရင္ေတာာ့ over write လို ္မာ ပ္။
>>> w={"house":"Haus","cat":"Katze","red":"rot"}
>>> w1 = {"red":"rouge","blau":"bleu"}
>>> w.update(w1)
>>> print w
{'house': 'Haus', 'blau': 'bleu', 'red': 'rouge', 'cat': 'Katze'}
dictionary
{"list":"Liste", "dictionary":"Wörterbuch", "function":"Funktion"}
List
[("list","Liste"),("dictionary","Wörterbuch"), ("function","Funktion")]
Sets in Python
“set” data type က collection type ျ စ္ျ ါးေတာာ့ python 2.4 ကစ ပလာ ပတမ္္။ set မ
ဲ ာ
immutable object ေတြ ပ ပတမ္္။ Set data type က mathematic set ကို python အေပနပနဲာ့
အသံိုးျ ဳေပနိုင္ေအာင္ေအရးသား ားတာ ဲျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ set မာ list ေတြ tuple ေတြလို
element ေတြ မ ္ ပဘး္။
Creating Sets
Set တစ္ ို ပန္တါး င္အရင္ sequence တစ္ ို သိုန္႔ Iterable obect တစ္ ိုကို set function သံိုးျ ါး
ပန္တါးပနင္ ပတမ္္။
>>> x = set("A Python Tutorial")
>>> x
set(['A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y', 'T'])
>>> type(x)
<type 'set'>
>>>
Immutable Sets
Set မ
ဲ ာ mutable object ေတြ ပလိုန္႔မအရ ပဘး္။ eg.
>>> cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))
>>> cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
Set မ
ဲ ာ mutable Object ပလိုန္႔မအရေ မမ္ာ့္။ set ကေတာာ့ mutable ျ စ္ ပတမ္္။
>>> cities = set(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
>>> cities
set(['Freiburg', 'Basel', 'Frankfurt', 'Strasbourg'])
>>>
Simplified Notation
Python 2.6 ကေပနစျ ါးေတာာ့ set function မသံိုး ဲ set ေတြ ပန္တါးပနိုင္ ပတမ္္။ {}သံိုး ပတမ္္။
>>> adjectives = {"cheap","expensive","inexpensive","economical"}
>>> adjectives
set(['inexpensive', 'cheap', 'expensive', 'economical'])
>>>
Set Operations
add(element)
copy
difference()
set ေတြႀကား က
ဲ ျ ားပနားမကို set အသစ္တစ္ ိုအေပနပနဲာ့ ိုတ္ေ း ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> y = {"b","c"}
>>> z = {"c","d"}
>>> x.difference(y)
set(['a', 'e', 'd'])
>>> x.difference(y).difference(z)
set(['a', 'e'])
>>>
“-“ operator သံိုးလည္းအရ ပတမ္္။
>>> x - y
set(['a', 'e', 'd'])
>>> x - y - z
set(['a', 'e'])
>>>
Set တစ္ ို ဲက element ကို အျ ား set တစ္ ို ဲက element ေတြ မ္ျ င္အရင္သံိုး ပတမ္ ္။
discard(el)
remove(el)
discard() ပနဲာ့တ ပတမ္္။ ဒပေ မမ္ာ့ သက မ္ င္တာ့ဲ element မ ပအရင္ KeyError ေ း ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> x.remove("a")
>>> x
set(['c', 'b', 'e', 'd'])
>>> x.remove("z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
>>>
intersection(s)
isdisjoint()
issubset()
x.issubset(y) က True ိုတ္ေ း ပလမ္ာ့မမ္္။ x က y အရဲာ့ subset ဆိုအရင္ေ ပာ့ ္။ "<=" ဆိုအရင္
subset of “>=” ဆိုအရင္ superset of “<” ကေတာာ့ subset ျ စ္မျ စ္စစ္ င္အရင္သံိုး ပတမ္္။ eg
က ိုအရင္း ပလမ္ာ့မမ္္။
>>> x = {"a","b","c","d","e"}
>>> y = {"c","d"}
>>> x.issubset(y)
False
>>> y.issubset(x)
True
>>> x < y
False
>>> y < x # y is a proper subset of x
True
>>> x < x # a set can never be a proper subset of oneself.
False
>>> x <= x
True
>>>
pop()
Set element ေတြကိုတစ္ ို င္း ိုတ္ေ း မ္ေ း ပတမ္္။ Empty ျ စ္သာြ းအရင္ေတာာ့ KeyError
ိုတ္ေ း ပတမ္္။
>>> x = {"a","b","c","d","e"}
>>> x.pop()
'a'
>>> x.pop()
'c'
Data Types and Variables အ ပန္းမာေျ ာ ဲာ့သလို integer / string ေတြလို data type
အရိုးအရိုးေလးေတြ assignment လို ္တာ copy လို ္တာမာ တစ္ျ ား programming language
ေတြပနဲာ့စာအရင္ python မာ ျ ားတဲာ့ ံိုစံေတြအရ ပတမ္္။ shallow ပနဲာ့ deep copying ကေတာာ့ list
လို class instance(object) လို object မ
ဲ ာ object ပတာေတြမာ အသံိုးျ ဳေ ိုန္႔သင္န္႔ေတာ္ ပတမ္္။
List ေတြ dictionary လို က mutable object ေတြ copy လို ္အရင္ဘာျ စ္မလဲႀကည္ာ့အရေအာင္
Copying a list
>>> colours1 = ["red", "green"]
>>> colours2 = colours1
>>> colours2 = ["rouge", "vert"]
>>> print colours1
['red', 'green']
colours1 က
ဲ ို list တစ္ ိုျ း ည္ာ့ colour2 ဲကို colour1 assign လို ္ ား ပတမ္္။ ျ ါးေတာာ့
colour2 က
ဲ ို list အသစ္တစ္ ို assign လို ္ ပတမ္္။
ေမ ာ္လင္ာ့ ားသလို ဲ colour1 တပန္ ိုးကမေျ ာင္း ပဘး္။ "Data types and variables" တိုပန္းက
လို ဲ colours2 အတြက္ memory location အသစ္တစ္ ိုေ းသြား ပတမ္္။ ဘာလိုန္႔လဆ
ဲ ိုေတာာ့
ကြ ပန္ေတာ္တိုန္႔ colours2 ကို assign ္လို ္လို္က္တာက list အသစ္တစ္ ိုျ စ္ေပနလိုန္႔ ပ္။
>>> colours1 = ["red", "green"]
>>> colours2 = colours1
>>> colours2[1] = "blue"
>>> colours1
['red', 'blue']
ဒါမာေမးစအရာစလာ ပျ ါ္။ colour2 သိုန္႔ colour1 ဲက element တစ္ ိုကိုေျ ာင္းလိုက္အရင္ေအရာ?
List အသစ္တစ္ ို assign လို ္တာမဟိုတ္ ဲ္။ list ဲက element တစ္ ိုကို ဲ
ေျ ာင္းလိုက္တာေႀကာင္ာ့ ျ စ္ ပတမ္္။
ဒါလိုမျ စ္ေအာင္ “copy” module ကိုသံိုးအရ ပမမ္္။ သန္႔မာ list ေတြအတြက္ “copy” method
ပ ပတမ္္။
from copy import deepcopy
lst1 = ['a','b',['ab','ba']]
lst2 = deepcopy(lst1)
lst2[2][1] = "d"
lst2[0] = "c";
print lst2
print lst1
Syntax
Parameter list ကေတာာ့ ဘာမမ ပတာျ စ္ပနိုင္လို တစ္ ို က္ ိုတာလဲျ စ္ပနိုင္ ပတမ္္။ function
call လို ္အရင္ parameter ေတြကို argument လိုန္႔လည္းေ ခ ပတမ္္။ function body မ
ဲ ာေတာာ့
indent လို ္ ားတဲန္႔ statement ေတြ ပ ပတမ္္။ function call လို ္တိုင္း function body ဲက
statement ေတြ execute လို ္ ပတမ္္။ paramameter ေတြက mandatory(မ ပမျ စ္)
ျ စ္ပနင္သလို optional(ေအရြး မ္ပနိုင္) လည္းျ စ္ပနိုင္ ပတမ္္။ optional parameter ေတြက
mandatory parameter ေပနာက္မာအရအရ ပမမ္္။
Docstring
Function body အရဲာ့ မဆံိုး statement က string တစ္ေႀကာင္း ားတတ္ ပတမ္္။ အဲာ့ဒါ string
ကို function_name.__doc_ ပနဲန္႔အရမသံိုးစြဲပနိုင္ ပတမ္္။ Docstring လိုန္႔ေ ခ ပတမ္္။
>>> execfile("function1.py")
>>> add.__doc__
'Returns x plus y'
>>> add2.__doc__
'Returns x plus y, optional'
>>>
Keyword Parameters
Definition
Definition of Recursion
Function တစ္ ိုက မမကိုမ္ကို function call ျ ပန္လို ္မမ္္။ function call လို ္တဲာ့ value ကို
return ျ ပန္ေ း ပတမ္္။
Termination condition:
အစား ိုး
4! = 4 * 3 * 2 * 1
print(factorial(5))
result က
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120
120
Fibonacci numbersေတြကေတာာ့
0,1,1,2,3,5,8,13,21,34,55,89, .
သတိုန္႔ကိုသတ္မတ္တာကေတာာ့
Fn = Fn-1 + Fn-2
with F0 = 0 and F1 = 1
iterative solution
def fibi(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
fibi() က fib() က္ ိုျမပန္ ပတမ္္။ ဘမ္ေလာက္ျမပန္လသ
ဲ င္အရင္ timeit module သံိုးအရ ပမမ္္။
from timeit import Timer
from fibo import fib
for i in range(1,41):
s = "fib(" + str(i) + ")"
t1 = Timer(s,"from fibo import fib")
time1 = t1.timeit(3)
s = "fibi(" + str(i) + ")"
t2 = Timer(s,"from fibo import fibi")
time2 = t2.timeit(3)
print("n=%2d, fib: %8.6f, fibi: %7.6f, percent: %10.2f" % (i,
time1, time2, time1/time2))
time1 ကေတာာ့ fib() အတြက္ time2 ကေတာာ့ fibi() အတြက္ျ စ္ ပတမ္္။ result ကိုႀကည္ာ့အရင္
fib(20) ကို ၃ ပေ ခအရင္ 14 milliseconds ႀကာတမ္္။ fibi(20) ကေတာာ့ ၃ ႀကမ္ေ ခအရာမာ 0.011
milliseconds ဲလို ပတမ္္။ ဒပေႀကာင္ာ့ fibi(20) က fib(20) က္ အဆ ၁၃၀၀ ျမပန္ ပတမ္္။
fibi():မစ္ႀကည္ာ့အရေအာင္
from timeit import Timer
from fibo import fib
for i in range(1,41):
s = "fibm(" + str(i) + ")"
t1 = Timer(s,"from fibo import fibm")
time1 = t1.timeit(3)
s = "fibi(" + str(i) + ")"
t2 = Timer(s,"from fibo import fibi")
time2 = t2.timeit(3)
print("n=%2d, fib: %8.6f, fibi: %7.6f, percent: %10.2f" % (i,
time1, time2, time1/time2))
iterative က္ေတာင္ ိုျမပန္တာေတြန္႔ ပလမ္ာ့မမ္္။
n= 1, fib: 0.000011, fibi: 0.000015, percent: 0.73
n= 2, fib: 0.000011, fibi: 0.000013, percent: 0.85
n= 3, fib: 0.000012, fibi: 0.000014, percent: 0.86
n= 4, fib: 0.000012, fibi: 0.000015, percent: 0.79
n= 5, fib: 0.000012, fibi: 0.000016, percent: 0.75
n= 6, fib: 0.000011, fibi: 0.000017, percent: 0.65
n= 7, fib: 0.000012, fibi: 0.000017, percent: 0.72
n= 8, fib: 0.000011, fibi: 0.000018, percent: 0.61
n= 9, fib: 0.000011, fibi: 0.000018, percent: 0.61
n=10, fib: 0.000010, fibi: 0.000020, percent: 0.50
n=11, fib: 0.000011, fibi: 0.000020, percent: 0.55
n=12, fib: 0.000004, fibi: 0.000007, percent: 0.59
n=13, fib: 0.000004, fibi: 0.000007, percent: 0.57
n=14, fib: 0.000004, fibi: 0.000008, percent: 0.52
n=15, fib: 0.000004, fibi: 0.000008, percent: 0.50
n=16, fib: 0.000003, fibi: 0.000008, percent: 0.39
n=17, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=18, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=19, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=20, fib: 0.000003, fibi: 0.000010, percent: 0.29
n=21, fib: 0.000004, fibi: 0.000009, percent: 0.45
n=22, fib: 0.000004, fibi: 0.000010, percent: 0.40
n=23, fib: 0.000004, fibi: 0.000010, percent: 0.40
n=24, fib: 0.000004, fibi: 0.000011, percent: 0.35
n=25, fib: 0.000004, fibi: 0.000012, percent: 0.33
n=26, fib: 0.000004, fibi: 0.000011, percent: 0.34
n=27, fib: 0.000004, fibi: 0.000011, percent: 0.35
n=28, fib: 0.000004, fibi: 0.000012, percent: 0.32
n=29, fib: 0.000004, fibi: 0.000012, percent: 0.33
n=30, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=31, fib: 0.000004, fibi: 0.000012, percent: 0.34
n=32, fib: 0.000004, fibi: 0.000012, percent: 0.33
n=33, fib: 0.000004, fibi: 0.000013, percent: 0.30
n=34, fib: 0.000004, fibi: 0.000012, percent: 0.34
n=35, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=36, fib: 0.000004, fibi: 0.000013, percent: 0.31
n=37, fib: 0.000004, fibi: 0.000014, percent: 0.29
Exercises
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
4. You find further exercises on our Python3 version of recursive functions, e.g. creating the
Fibonacci numbers out of Pascal's triangle or produce the prime numbers recursively, using
the Sieve of Eratosthenes.
def pascal(n):
if n == 1:
return [1]
else:
p_line = pascal(n-1)
line = [ p_line[i]+p_line[i+1] for i in range(len(p_line)-1)]
line.insert(0,1)
line.append(1)
return line
print(pascal(6))
Debugging and testing ဆိုတာလည္း programmer မ ားအ ပန္မ ားမ ားေ းအရတဲာ့ အဆင္ာ့ ပ ဲ္။
အမ ဳေးမ ဳေးေသာအေႀကာင္း အအရာေတြေ ခမတည္တာ့အ
ဲ တြက္ လည္း ဘမ္ေလာက္အ ပန္ေ းအရမမ္ာ့
ဆိုတာေျ ာအရ က္ ပတမ္္။
Kinds of Errors
Error အမ ်ဴးမ ဳေးအရ ပတမ္္။ typo error မ ဳေး စကားလံိုးေတြမားတာ က ပန္တာ ေတြကို syntactical
error လိုန္႔ေ ခ ပတမ္္။
if x > 10:
if y == x:
print("Fine")
else:
print("So what?")
x = int(input("x? "))
y = int(input("y? "))
if x > 10:
if y == x:
print("Fine")
else:
print("So what?")
ႏွာစ္ ိုစလံိုးက syntactically မပန္ ပတမ္္။ ဒပေ မမ္ာ့ တစ္ ိုက လို င္သလို
(semantic)အလို ္မလို ္ ပဘး္။
Unit Tests
Code ေတြ က
ဲ တစ္စတ္တစ္ ိုင္းေတြျ စ္တာ့ဲ class ေတြ function ေတြ စမ္းအရင္သံိုး ပတမ္္။
သေဘာကေတာာ့ system ႀကါးကို unit ေလးေတြအျ စ္ ိုင္းျ ါး စစ္ေဆးတာျ စ္ ပတမ္္။ ဒါလို
စမ္းသ ္ ိုန္႔အတြက္ လည္း program ေတြကို စမ္းသ ္လိုန္႔အရတဲာ့ unit ေတြ ြျဲ ားအရ ပတမ္္။
Module တိုင္းမာ ပနာမည္ အရ ပတမ္္။ built in attribute တစ္ ိုျ စ္တာ့ဲ __name__ ပနဲန္႔သတ္မတ္
ား ပတမ္္။ xyz ဆိုတဲန္႔ module ေအရးျ ါး xyz.py လိုန္႔သမ္း ားတမ္ဆို ပစိုန္႔္။ “import xyz” ပနဲန္႔
import လို ္တဲာ့အ ပ __name__ က
ဲ ို xyz ဆိုတဲာ့ string ေအရာက္သြား ပတမ္္။ xyz.py ကို
standalone သံိုးမမ္ဆိုအရင္ေတာာ့
$python xyz.py
__name__ မ
ဲ ာအရမမမ္ာ့တပန္ ိုး က '__main__' ဆိုတဲာ့ string တပန္ ိုးျ စ္မာ ပ္။
def fiblist(n):
""" creates a list of Fibonacci numbers up to the n-th generation """
fib = [0,1]
for i in range(1,n):
fib += [fib[-1]+fib[-2]]
return fib
Python shell မာ ဒါModule ကိုစမ္း င္အရင္လည္းအရ ပတမ္္။
>>> from fibonacci import fib, fiblist
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fiblist(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> fiblist(-8)
[0, 1]
>>> fib(-1)
0
>>> fib(0.5)
Traceback (most recent call last):
File "", line 1, in
File "fibonacci.py", line 6, in fib
for i in range(n):
TypeError: 'float' object cannot be interpreted as an integer
>>>
Positive integer ေတြ ဲဆိုအရင္ေတာာ့ မပန္ေပနတာ ေတြန္႔ ပလမ္ာ့မမ္္။ negative input ဆို fib
function က 0 return ျ ပန္ျ ါး fiblist က [0,1] ဲ return ျ ပန္ ပလမ္ာ့မမ္္။ float
ည္ာ့ေ းအရင္ေတာာ့ ႏွာစ္ ိုလံိုးက error ျ ပလမ္ာ့မမ္္။
Module test လို ္ ိုန္႔အတြက္ fib() ပနဲန္႔ fiblist() ကို ပနံ ပတ္ေတြပနဲrာ့ eturn
ေတြအသံိုးျ ဳေစစ္ေဆးပနိုင္ ပတမ္္။
if fib(0) == 0 and fib(10) == 55 and fib(50) == 12586269025:
print("Test for the fib function was successful!")
else:
print("The fib function is returning wrong values!")
standalone သံိုးအရင္ေအာက္ ပအတိုင္းျမင္အရ ပလ္မ္ာ့မမ္္။
def fib(n):
""" Calculates the n-th Fibonacci number iteratively """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def fiblist(n):
""" creates a list of Fibonacci numbers up to the n-th generation """
fib = [0,1]
for i in range(1,n):
fib += [fib[-1]+fib[-2]]
return fib
if __name__ == "__main__":
if fib(0) == 0 and fib(10) == 55 and fib(50) == 12586269025:
print("Test for the fib function was successful!")
else:
print("The fib function is returning wrong values!")
ဒပဆို module import လို ္အရင္ျမင္အရေတာာ့မာမဟိုတ္ ပဘး္။အအရင္းဆံိုး module test ပ ဲ
အေကာင္း ဆံိုးေတာာ့မဟိုတ္ ပဘး္။
def fib(n):
""" Calculates the n-th Fibonacci number iteratively """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
import လို ္ျ ါးစမ္းႀကည္ာ့ ပမမ္္။
>>> from fibonacci import fib
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610
>>>
စမ္း ားတဲာ့ တစ္ ိုလံိုးကို function အရဲာ့ docstring မ
ဲ ာ ည္ာ့ ပမမ္္။ test လို ္တဲာ့အ ပမာ module
ကို srandalone သံိုးအရင္ေတာာ့ testmod() ကို ေ ခေ းအရ ပမမ္္။
import doctest
def fib(n):
"""
Calculates the n-th Fibonacci number iteratively
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610
>>>
"""
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
if __name__ == "__main__":
doctest.testmod()
ဒါပနည္းလမ္းအတြက္ က္ တ
ဲ ာက သင္ေလ ာ္တာ့ဲ test case ေတြျ စ္ ပတမ္္။ အေကာင္းဆံိုး test
case ကေတာာ့ ျ စ္ပနိုင္တာ့ဲ input အားလံိုးပနဲo
ာ့ utput ေတြကို စစ္ေဆး ပလမ္ာ့မမ္္။ လက္ေတြန္႔မာေတာာ့
မျ စ္ပနိုင္ ပဘး္။
def fib(n):
"""
Calculates the n-th Fibonacci number iteratively
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(15)
610
>>>
"""
return 0
if __name__ == "__main__":
doctest.testmod()
ဒပေႀကာင္ ာ့fib(0) အတြက္ကလြျဲ ါးက ပန္တာေတြကို error ေတြေ း ပလမ္ာ့မမ္္။
$ python3 fibonacci_TDD.py
**********************************************************************
File "fibonacci_TDD.py", line 10, in __main__.fib
Failed example:
fib(1)
Expected:
1
Got:
0
**********************************************************************
File "fibonacci_TDD.py", line 12, in __main__.fib
Failed example:
fib(10)
Expected:
55
Got:
0
**********************************************************************
File "fibonacci_TDD.py", line 14, in __main__.fib
Failed example:
Unittest
Python module တစ္ ိုျ စ္တာ့ဲ unittest ကေတာာ့ unit testing framework တစ္ ိုျ စ္ျ ါး Erich
Gamma's JUnit and Kent Beck's Smalltalk testing framework ေ ခမာ အေျ ံ
တည္ေဆာက္ ား ပတမ္္။ ဒါmodule မ
ဲ ာ test case and suits ေတြ ၊ test ေတြ လို ္ ိုန္႔ text-
based utility class ေတြ result ေတြ ၊report လို ္ ိုန္႔ေတြ(TextTestRunner) ေတြ ပ၀င္ ပတမ္္။
ျ ါးေတာာ့ unittest.TestCase ကို inherit လို ္ ားတဲာ့ class တစ္ ိုလိုမမ္ “FibonacciTest”
လိုန္႔ေ ခ ပမမ္္။ test case ေတြကို ဒါ class မ
ဲ ာ method ေတြသံိုးျ ါးသတ္မတ္ ပမမ္္။ method
name ေတြကႀကိုက္တာျ စ္လိုန္႔အရေ မမ္ာ့ test ပနဲန္႔စအရ ပမမ္္။ "testCalculation" မ
ဲ ာ TestCase.
assertEqual class ဲက assertEqual method ကိုသံိုး ား ပတမ္္။ “first” expression ပနဲာ့
“second” expression တလားစစ္တာ ပ္။ မတအရင္ msg ကို output ိုတ္ေ း ပလမမ္ာ့မမ္္။
import unittest
from fibonacci import fib
class FibonacciTest(unittest.TestCase):
def testCalculation(self):
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(5), 5)
self.assertEqual(fib(10), 55)
self.assertEqual(fib(20), 6765)
if __name__ == "__main__":
unittest.main()
OK
လို င္တဲာ့ result ပ ဲ ္။ error ေတြစမ္းႀကည္ာ့ ပမမ္္။
a, b = 0, 1
ကို ေ
ဲ ျ ာင္းႀကည္ာ့ ပစါးမမ္္။
a, b = 1, 1
ဒပဆိုအရင္ေတာာ့
$ python3 fibonacci_unittest.py
F
======================================================================
FAIL: testCalculation (__main__.FibonacciTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "fibonacci_unittest.py", line 7, in testCalculation
self.assertEqual(fib(0), 0)
AssertionError: 1 != 0
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
testCalculation အရဲာ့ မဆံိုးအေႀကာင္းမာ error ျ ပတမ္္။ တစ္ျ ား assertEqual ေတြက
execute မလို ္ေသး ပဘး္။ error ကိုျ င္ျ ါ ေပနာက္တစ္ ိုလို ္ႀကည္ာ့အရေအာင္္။ ဒါတစ္ ပက 20
အတြက္ကလဲြျ ါး က ပန္တာ မပန္ ပလမ္ာ့မမ္္။
def fib(n):
""" Iterative Fibonacci Function """
a, b = 0, 1
for i in range(n):
a, b = b, a + b
if n == 20:
a = 42
return a
ဒါတစ္ ပမာေတာာ့
$ python3 fibonacci_unittest.py
blabal
F
======================================================================
FAIL: testCalculation (__main__.FibonacciTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "fibonacci_unittest.py", line 12, in testCalculation
self.assertEqual(fib(20), 6765)
AssertionError: 42 != 6765
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
Method Meaning
tearDown()
Hook method for deconstructing the class fixture after
running all tests in the class.
assertEqual(self, first, The test fails if the two objects are not equal as
second, msg=None) determined by the '==' operator.
assertDictEqual(self, d1, d2, Both arguments are taken as dictionaries and they are
msg=None) checked if they are equal.
assertTrue(self, expr,
msg=None) Checks if the expression "expr" is True.
assertGreaterEqual(self, a,
b, msg=None) Checks if a ≥ b
assertFalse(self, expr,
msg=None) Checks if expression "expr" is False.
assertLess(self, a, b,
msg=None) Checks if a < b
assertLessEqual(self, a, b,
msg=None) Checks if a ≤ b
assertIn(self, member,
container, msg=None) Checks if a in b
assertIsInstance(self, obj,
cls, msg=None) Checks if isinstance(obj, cls).
assertIsNone(self, obj,
msg=None) Checks if "obj is None"
assertIsNot(self, expr1,
expr2, msg=None) Checks if "a is not b"
assertIsNotNone(self, obj,
msg=None) Checks if obj is not equal to None
assertListEqual(self, list1,
list2, msg=None) Lists are checked for equality.
assertMultiLineEqual(self,
first, second, msg=None) Assert that two multi-line strings are equal.q
assertNotRegexpMatches(self,
text, unexpected_regexp,
Fails, if the text Text "text" of the regular expression
msg=None) unexpected_regexp matches.
assertTupleEqual(self,
tuple1, tuple2, msg=None) Analogous to assertListEqual
class FibonacciTest(unittest.TestCase):
def setUp(self):
self.fib_elems = ( (0,0), (1,1), (2,1), (3,2), (4,3), (5,5) )
print ("setUp executed!")
def testCalculation(self):
for (i,val) in self.fib_elems:
self.assertEqual(fib(i), val)
def tearDown(self):
self.fib_elems = None
print ("tearDown executed!")
if __name__ == "__main__":
unittest.main()
result ကေတာာ့
$ python3 fibonacci_unittest2.py
setUp executed!
tearDown executed!
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
TestCase methods ေတြေတာ္ေတာ္မ ားမ ားမာ optional parameter “msg” ပ ပတမ္္။ msg ပနဲာ့
error အတြက္အေႀကာင္းအအရာေတြ ္ ည္ာ့ေ းလိုန္႔အရ ပတမ္္။
1. Exercise:
def fib(n):
""" Calculates the n-th Fibonacci number iteratively
>>> fib(0)
0
>>> fib(1)
1
>>> fib(10)
55
>>> fib(40)
102334155
>>>
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
if __name__ == "__main__":
doctest.testmod()
Answer:
The doctest is okay. The problem is the implementation of the fibonacci function. This recursive
approach is "highly" inefficient. You need a lot of patience to wait for the termination of the test.
The number of hours, days or weeks depend on your computer.☺
ျ ပနာက recursive fib function ကို ျ င္လိုက္လိုန္႔ျ စ္တာ ပ္။ ေအာက္ေ ာ္ျ ပ code မာေတာာ့
fib function ကိုမျ င္ ား ပဘး္။ ဒပေႀကာင္ာ့ memoize ဆိုတဲာ့ function တစ္ ိုသံိုး ား ပတမ္္။
memoize() က function တစ္ ိုကို argument အေပနပနဲာ့လက္ ံေ း ပတမ္္။ memoize()
function က “memo” ဆိုတဲာ့ dictionary သံိုးျ ါး result ေတြကိုမတ္ ပတမ္္။ “memo”ေအရာ “f”
ေအရာ local value ေတြဆိုေ မမ္ာ့ helper method ေတြသံိုးျ ါး return ျ ပန္ ပတမ္္။
memoize(fib) ကိုေ ခတဲာ့ အ ပမာ helper() အရဲာ့ referenceအရမ္ တြက္ ားတဲာ့ result သမ္း ားတဲာ့
wrapper အရမ္ျ ပန္ေ း ပတမ္္။
def memoize(f):
memo = {}
def helper(x):
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
fib = memoize(fib)
print(fib(40))
fib ကa
ို rgument အေပနပနဲာ့သံိုး ားတဲာ့ အေႀကာင္းကိုႀကည္ာ့အရေအာင္
fib = memoize(fib)
ဒပဆိုအရင္ memoize က decorator ျ စ္သာြ း ပတမ္္။ fib = memoize(fib) အလို ္မလို ္ င္
function name ေတြက သတိုန္႔ body ကို ဲ reference လို ္ ပတမ္္။
fib = memoize(fib)ကို execute လို ္ျ ါးတဲာ့အ ပန္မာေတာာ့ fib က helper function body ကို
ညြပန္း ပတမ္္။ မလ fib function ကိုလဲ helper အရဲာ့ f function ကေပနမတဆင္ာ့သာြ းလိုန္႔အရေတာာ့မာ ျ
ျ စ္ ပတမ္္။ fib အတြက္ တစ္ျ ား reference မအရေတာာ့ ပဘး္။ decorate လို ္ ားတဲာ့ Fibonacci
function ကို return fib(n-1) + fib(n-2)ပနဲန္႔ေ ခ ား ပတမ္္။ memorize ကေပန return
ျ ပန္လာ တဲာ့ helper function ကိုေျ ာတာျ စ္ ပတမ္္။
decorator ဲက context ေတြကအျ ား အဓ ၸာမ္အရ ပေသးတမ္္။ function
ေတြအျမားႀကါးေအရးမည္ာ့ အစား”memorize” ပနဲာ့ decorate လို ္တာျ စ္ ပတမ္္။
fib = memoize(fib)
func1 = memoize(func1)
func2 = memoize(func2)
func3 = memoize(func3)
# and so on
Decorator ကို python မာေအရးသလိုေအရးမ ား ပဘး္။ေအာက္ ပအတိုင္းေအရးမမ္ာ့အစား
fib = memoize(fib)
fib ကို “decorated” လို ္သင္ာ့ ပတမ္္။
@memoize
ဒပေ မမ္ာ့ ဒါစာေႀကာင္းက decorated function ေအရာ့မာအရအရမာ ပ္။
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return memo[x]
return helper
@memoize
def fib(n):
if n == 0:
return 0
print(fib(40))
Using a Class Decorator for Memoization
@Memoize
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
dictionary သံိုးတဲာ့အတြက္ေႀကာင္ာ့ mutable argument ေတြသိုးံ လိုန္႔မအရ ပဘး္။
Call by Value
Call by Reference
def ref_demo(x):
Side effects
Python script ကို command line argument ေတြသံိုးျ ါးေအရးပနိုင္ ပတမ္္။ python script
ေတြကို shell ကေပနအသံိုးျ ဳေတာ့အ
ဲ ပမာ argument ေတြက script name
* in Function Calls
“*” က function call လို ္အရာမာလည္း ပလာပနိုင္ ပတမ္္။ tuple ေတြ List ေတြဆိုအရင္ singular
ံိုစံေျ ာင္းသြား ပတမ္္။
>>> def f(x,y,z):
... print(x,y,z)
...
>>> p = (47,11,12)
>>> f(*p)
(47, 11, 12)
ေအာက္ ပ ံိုစံအတိုင္းလည္းအရ ပတမ္္။
>>> f(p[0],p[1],p[2])
(47, 11, 12)
>>>
Namespaces
Lifetime of a Namespace
Scopes
အတြင္းအက ဆံိုး scope မာ အအရင္အရာျ ါးေတာာ့ ၎မာ local name ေတြ ပ ပတမ္္။
တကမ္လိုန္႔ တစ္ျ ား scope တစ္ ို ဲမာအရတမ္ဆိုအရင္လည္း အပနါးဆံိုးကို အအရင္အရာ ပတမ္္။
ေပနာက္ scope ေတြမာေတာာ့ လက္အရ Module အရဲာ့ global name ေတြ ပ ပတမ္္။
အျ င္အက ဆံိုးပနဲာ့ ေပနာက္ဆံိုးကေတာာ့ built-in name ေတြ ပတဲာ့ namespace ျ စ္ ပတမ္္။
s = "Python is great!"
f()
print s
run ႀကည္ာ့အရင္ error ျ ပလမ္ာ့မမ္္။
I am globally not known
Traceback (most recent call last):
File "global_local3.py", line 6, in <module>
print s
NameError: name 's' is not defined
a,b,x,y = 1,15,3,4
foo(17,4)
print a,b,x,y
The output of the script above looks like this:
42 17 4 17
42 15 3 4
File ဆိုတာကေတာာ့ program ေတြကေပန data ေတြinformation ေတြစို ားတဲာ့ computer file
ေတြျ စ္ ပတမ္္။ file ေတြကို durable storage ေတြမာသမ္း ပတမ္္။ လေတြ program
ေတြကေပန file ေတြကို တ္အရျ င္ဆင္ တာေတြလို ္ ိုန္႔အတြက္ unique name ပနဲာ့ path
ေတြအသံိုးျ ဳေႀက ပတမ္္။
File manipulation မာ ပတဲာ့ အဓကလို ္ေဆာင္ က္ေတြကေတာာ့ file ေတြကေပန data ေတြ
တ္တာေတြ data ေတြျ ပန္ ည္ာ့တာ ္ေ ပာင္းတာေတြျ စ္ ပတမ္္။
File ကေပန data တ္ႀကည္ာ့ ပတမ္္။ မ parameter ကေတာာ့ အသံိုးျ ဳေမမ္ာ့ file name
ျ စ္ျ ါးေတာာ့ ဒိုတမ parameter ကေတာာ့ “r” လိုန္႔ေ း ားျ ါး read
လို ္မမ္လိုာ့ေျ ာတာျ စ္ ပတမ္္။
fobj = open("ad_lesbiam.txt", "r")
file ပနဲာ့ တ္သတ္တာ့ဲ အလို ္ေတြလို ္ျ ါးအရင္ေတာာ့ close လို ္ေ းအရ ပမမ္္။
fobj.close()
examples
fobj = open("ad_lesbiam.txt")
for line in fobj:
print line.rstrip()
fobj.close()
“file_read.py”လိုန္႔သမ္းျ ါး runႀကည္ာ့အရင္
$ python file_read.py
V. ad Lesbiam
Reading in one
Python မာ “pickle”လိုန္႔ေ ခတဲာ့ Module တစ္ ို ပ ပတမ္္။ pickle module သံိုးျ ါးေတာာ့ python
object ေတြကို serialize / de-serialize လို ္ပနင္ ပတမ္္။ “pickilng” ဆတ
ို ာကေတာာ့ python
object ေတြကို byte stream အျ စ္ေျ ာင္းလဲတာျ စ္ျ ါး ္။ “unpickling”ကေတာာ့
ေျ ာင္းျ ပန္ျ စ္ ပတမ္္။ byte stream ကေပန python object ေျ ာင္းေ းတာ ပ္။ pickling and
unpickling ကို data structre ကို “serialization” သိုန္႔ “flattening”လိုန္႔လည္းသႀက ပတမ္္။
Pickle module အရဲာ့ dump method ပနဲန္႔ dump(ေျ ာင္းလဲ) ပနိုင္ ပတမ္္။
pickle.dump(obj, file[,protocol])
object “obj”အရဲာ့ serialized version က file က
ဲ ိုေအရာက္သြား ပမမ္္။ protocol ကေတာာ့ object
ကိုဘမ္လို write လို ္မလဲေျ ာတာ ပ္။
0=ascii
1=compact (not human readable)
2=optimised classes
Modular Programming
Python မာ module ဆိုတာကေတာာ့ python statement ေတြ definition ေတြ ပတဲာ့ file
တစ္ ို ပ ဲ္။ module ပနာမည္ကေတာာ့ file name ဲျ စ္ ပတမ္္။ ေပနာက္က file extension ျ စ္တာ့ဲ
.py ည္ာ့စာမလို ပဘး္။ fibonacci.py ဆိုအရင္ Module name က Fibonacci ျ စ္ ပတမ္္။
eg.fibonacci.py
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def ifib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
ဒါmodule ကို interactive shell မာ Import လို ္ျ ါးအသံိုးျ ဳေပနိုင္ ပတမ္္။
>>> import fibonacci
>>> fibonacci.fib(30)
832040
>>> fibonacci.ifib(100)
354224848179261915075L
>>> fibonacci.ifib(1000)
434665576869374564356885276750406258025646605173717804024817290895365554179
490518904038798400792551692959225930803226347752096896232398733224711616429
96440906533187938298969649928516003704476137795166849228875L
>>>
module function name ေတြကိုတိုသာြ းေအာင္ local name ေတြပနဲံအသံိုးျ ဳေပနိုင္ ပတမ္္။
>>> fib = fibonacci.ifib
>>> fib(10)
55
>>>
Module ေတြ မ
ဲ ာ function ေတြ ပပနို္င္သလို statement ေတြလည္း ပပနင္ ပတမ္္။ ၎
statement ေတြကို module initialize လို ္ ိုန္႔သံိုးပနိုင္ ပတမ္္။ ျ ါးေတာာ့ ၎ statement ေတြကို
module import လို ္တဲာ့အ ပမာ ဲ execute လို ္ ပတမ္္။
Module မာ အျ ား module ေတြကို import လို ္ပနိုင္ ပတမ္္။ script သိုန္႔ module ေတြမာ
Import ကိုအအရင္ ္ဆံိုးမာ ေအရးႀက ပတမ္္။
Module ဲက name ေတြကို import လို ္ေပနတဲာ့ module အရဲာ့ symbol table ဲ တိုက္အရိုက္
import လို ္ပနင္ ပတမ္္။
>>> from fibonacci import fib, ifib
>>> ifib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Local symbol table မ
ဲ ာေတာာ့ ဘမ္Module ကေပနimport
လို ္တမ္ဆိုတာအရမာမဟိုတ္ ပဘး္။ module မ
ဲ ာ အရတဲာ့ name အားလံိုးကို import
လို ္ပနိုင္ေ မမ္ာ့ recommend မေ း ပဘး္။
>>> from fibonacci import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
မလို ္သင္ာ့ေ မဲiန္႔ nteractive session ေတြမာ ေတာာ့ typing အရိုက္အရသက္သာေစ ပတမ္္။
အေအရးႀကါးတာတစ္ ိုက interpreter session တစ္ ိုမာ တစ္ ပ ဲ Import လို ္ပနိုင္ ပတမ္္။
တကမ္ လိုာ့module မာ ေျ ာင္းလဲမတစ္ ိုအရအရင္ interpreter ကို restart လို ္အရင္လို ္ မလို ္အရင္
reload(modulename) လို ္ေ းအရ ပမမ္္။
Python module ေတြဟာ script ေတြ ဲျ စ္တာေႀကာင္ာ့ script ေတြလို ဲ run ပနင္ ပတမ္္။
python fibo.py
Renaming a Namespace
Module Import လို ္တဲာ့အ ပ namespace အရဲာ့ name ကိုေျ ာင္းလဲပနိုင္ ပတမ္္။
>>> import math as mathematics
>>> print mathematics.cos(mathematics.pi)
-1.0
Namespace အရေပနေ မဲာ့ ပနာမည္ေတာာ့တေတာာ့မာမဟိုတ္ ပဘး္။ method အ ဳေန္႔ကို ဲ Import
လို ္ င္အရင္လည္းအရ ပတမ္္။
>>> from math import pi,pow as power, sin as sinus
>>> power(2,3)
8.0
>>> sinus(pi)
1.2246467991473532e-16
Kinds of Modules
Content of a Module
Module Packages
Package မ
ဲ ာ ပ၀င္တာ့ဲ directory တိုင္းမာ __init__.py ဆိုတဲာ့ file ပ၀င္အရ ပမမ္္။
မဟိုတ္အရင္ေတာာ့ import လို ္လိုန္႔မအရ ပဘး္။
“regular expression”ကို တစ္ ပတစ္အရံ regex သိုန္႔ rexexp လိုန္႔လည္းေ ခႀက ပတမ္္။
Text ေတြ textstring ေတြကို filtering လို ္ ိုန္႔ regular expression ေတြကသ
ို ံိုးႀက ပတမ္္။
Introduction
String sub=”abc”
အကိုပန္ကိုပန္လိုန္႔မမတအရင္ေတာာ့ s မ
ဲ ာ sub မ ပဘးေ ပာ့္။
ဒါစ မာမာ a ပနဲာ့ စတင္ျ ါး .html ပနဲာ့ အဆံိုးသတ္တဲာ့ file အားလံိုးျ စ္ ပတမ္္။
r”cat” ဆိုတာ regular expression တစ္ ို ပ္။ သက "A cat and a rat can't be friends." ပနဲာ့
ဆိုအရင္ match ျ စ္ ပတမ္္။
ဒပေ မမ္ာ့ဒါမာ အမားတစ္ ိုအရ ပတမ္္။ cat လိုန္႔ဆိုလိုေ မမ္ာ့ အျ ားစကားလံိုးေတြပနဲာ့လည္း ကိုက္ညါ
ေပန ပေသးတမ္္။ စ မာ “education” "communicate", "falsification", "ramifications",
"cattle” စသျ င္ာ့စကားလံိုးေတြ ပ ဲာ့အရင္လည္း match ျ စ္ေပန ပလမ္ာ့မမ္္။ ဒပကို “over
matching”လိုန္႔ဆို ပတမ္္။
ဒပကိုေအရာင္အရား င္တာ့အ
ဲ ပ r” cat ”ဆိုျ ါး ေဘးမာ black ေတြ ား င္ ားပနိုင္ ပတမ္္။
ိုပနစကားလံိုးေတြမ ပေတာာ့ေ မမ္ာ့ ေပနာက္ျ ပနာတစ္ ို ္ျ စ္ ပတမ္္။ "The cat, called
Oscar, climbed on the roof." မာဆိုအရင္ cat ေပနာက္မာ “,” ပလာတဲာ့အတြက္ match
မျ စ္ေတာာ့ ပ ဘး္။
Any Character
အေ ခမာျ ဲာ့တဲာ့ example လို cat ကိုမအရာ ဲ at ပနဲန္႔ အဆံိုးသတ္တဲန္႔ character သံိုးလံိုး ပ ကိုအရာမမ္္။
r“ .at ”
Character Classes
ဒပဆိုအရင္ေတာာ့ “-” ကိုသံိုးအရ ပမမ္္။ [a-e] ဆိုအရင္ [abcde] [0-5]ဆိုအရင္ [012345]ျ စ္ ပတမ္္။
“-” ကိုစကားလံိုးႀကားေတြ မ
ဲ ာမသံိုး ဲ ေအရာ့မာသိုန္႔ ေပနာက္မာသံိုးအရင္ေတာာ့ “-
”တစ္ ိုကိုဆိုလို ပတမ္္။ [-az] ဆိုအရင္ - or a or z လိုန္႔ဆိုလို ပတမ္္။
\d =[0-9]
\D=[^0-9]
\s=[\t\n\r\f\v]
\w=[a-zA-Z0-9]
\W=\w မဟိုတ္တာ
\B= empty string ျ စ္ျ ါးေတာာ့ စကားလံိုးတစ္ ိုအရဲာ့ေအရာ့ သိုန္႔ ေပနာက္မာ မအရအရဘး
\\=\
“^” က string အစကိုေျ ာတာျ စ္ ပတမ္္။ MULTILINE mode မာေတာာ့ newline စတိုင္း
match ျ စ္ ပတမ္္။
>>> import re
>>> s1 = "Mayer is a very common Name"
>>> s2 = "He is called Meyer but he isn't German."
>>> print re.search(r"^M[ae][iy]er", s1)
<_sre.SRE_Match object at 0x7fc59c5f26b0>
>>> print re.search(r"^M[ae][iy]er", s2)
None
Optional Items
Mayer ဆိုတဲာ့ ပနာမည္မာအအရင္ ပနာမည္ေတြအျ င္ e ကိုျ ဳေတ္ ားတဲာ့ ံိုစံေတြ ["Mayr", "Meyr",
"Meir", "Mair"] plus our old set ["Mayr", "Meyr", "Meir", "Mair"].အရ ပေသးတမ္္။
Quantifiers
Grouping
Regurlar expression ေတြကို group ြန္႔ဲ င္အရင္ () ပနဲန္႔ အသံိုးျ ဳေပနိုင္ ပတမ္္။
Re.search() method သံိုးတာမာ match ျ စ္အရင္ Match object return ျ ပန္ျ ါး မျ စ္အရင္ None
ပ္။ match object မ
ဲ ာ data ေတြအျမားအျ ား ပ၀င္ ပတမ္္။
Named Backreferences
In this comprehensive exercise, we have to bring together the information of two files. In the first
file, we have a list of nearly 15000 lines of post codes with the corresponding city names plus
additional information. Here are some arbitrary lines of this file:
68309,"Mannheim",8222,"Mannheim",8,"Baden-Wrttemberg"
68519,"Viernheim",6431,"Bergstraße",6,"Hessen"
68526,"Ladenburg",8226,"Rhein-Neckar-Kreis",8,"Baden-Württemberg"
68535,"Edingen-Neckarhausen",8226,"Rhein-Neckar-Kreis",8,"Baden-
Württemberg"
The other file contains a list of the 19 largest German cities. Each line consists of the rank, the name
of the city, the population, and the state (Bundesland):
1. Berlin 3.382.169 Berlin
2. Hamburg 1.715.392 Hamburg
3. München 1.210.223 Bayern
4. Köln 962.884 Nordrhein-Westfalen
5. Frankfurt am Main 646.550 Hessen
6. Essen 595.243 Nordrhein-Westfalen
7. Dortmund 588.994 Nordrhein-Westfalen
8. Stuttgart 583.874 Baden-Württemberg
9. Düsseldorf 569.364 Nordrhein-Westfalen
10. Bremen 539.403 Bremen
11. Hannover 515.001 Niedersachsen
12. Duisburg 514.915 Nordrhein-Westfalen
13. Leipzig 493.208 Sachsen
14. Nürnberg 488.400 Bayern
15. Dresden 477.807 Sachsen
16. Bochum 391.147 Nordrhein-Westfalen
17. Wuppertal 366.434 Nordrhein-Westfalen
18. Bielefeld 321.758 Nordrhein-Westfalen
19. Mannheim 306.729 Baden-Württemberg
Our task is to create a list with the top 19 cities, with the city names accompanied by the postal
code. If you want to test the following program, you have to save the list above in a file called
largest_cities_germany.txt and you have to download and save the list of German post codes
# -*- coding: iso-8859-15 -*-
import re
fh_post_codes = open("post_codes_germany.txt")
PLZ = {}
for line in fh_post_codes:
(post_code, city, rest) = line.split(",",2)
PLZ[city.strip("\"")] = post_code
fh_largest_cities = open("largest_cities_germany.txt")
Postcode units consist of between five and seven characters, which are separated into two parts by
a space. The two to four characters before the space represent the so-called outward code or out
code intended to direct mail from the sorting office to the delivery office. The part following the
space, which consists of a digit followed by two uppercase characters, comprises the so-called
inward code, which is needed to sort mail at the final delivery office. The last two uppercase
characters can be only one of these ABDEFGHJLNPQRSTUWXYZ
The outward code can have the form: One or two uppercase characters, followed by either a digit or
the letter R, optionally followed by an uppercase character or a digit. (We do not consider all the
detailed led rules for postcodes, i.e only certain character sets are valid depending on the position
and the context.)
A regular expression for matching this superset of UK postcodes looks like this:
r"\b[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}\b"
The following Python program uses the regexp above:
import re
Grouping ပနဲန္႔ backreference လည္းသအရ ပမမ္္။ ေပနာက္ျ ါးေတာာ့ re module အရဲာ့ match object
ေတြ သန္႔မာ ဘာ information ေတြ ပလ ဲ information ေတြကsို pan(), start(), end(), and
group() ေတြသံိုးျ ါးဘမ္လိုအရပနိုင္မလဲစသျ င္ာ့သအရ ပမမ္္။
Alternations
String ေတြကို substring ေတြအျ စ္ ိုင္းတဲံ split ဆိုတဲန္႔ string method တစ္ ိုအရ ပတမ္္။
str.split([sep[, maxsplit]])
Split မာ optional parameter ႏွာစ္ ိုအရတမ္္။ ဘာမမ ည္ာ့ေ းအရင္ white space ေတြသံိုးျ ါး
ိုင္းေ းမမ္္။
Exampls
>>> law_courses = "Let reverence for the laws be breathed by every American
mother to the lisping babe that prattles on her lap. Let it be taught in
schools, in seminaries, and in colleges. Let it be written in primers,
spelling books, and in almanacs. Let it be preached from the pulpit,
proclaimed in legislative halls, and enforced in the courts of justice.
And, in short, let it become the political religion of the nation."
>>> law_courses.split()
['Let', 'reverence', 'for', 'the', 'laws', 'be', 'breathed', 'by', 'every',
'American', 'mother', 'to', 'the', 'lisping', 'babe', 'that', 'prattles',
'on', 'her', 'lap.', 'Let', 'it', 'be', 'taught', 'in', 'schools,', 'in',
'seminaries,', 'and', 'in', 'colleges.', 'Let', 'it', 'be', 'written',
'in', 'primers,', 'spelling', 'books,', 'and', 'in', 'almanacs.', 'Let',
'it', 'be', 'preached', 'from', 'the', 'pulpit,', 'proclaimed', 'in',
'legislative', 'halls,', 'and', 'enforced', 'in', 'the', 'courts', 'of',
'justice.', 'And,', 'in', 'short,', 'let', 'it', 'become', 'the',
'political', 'religion', 'of', 'the', 'nation.']
>>>
White space အရတဲာ့ေပနအရာေတြကို ိုင္းေ းသြား ပတမ္္။ semicolon “;” ပနဲန္႔ဲ ိုင္းႀကည္ာ့အရေအာင္္။
>>> line = "James;Miller;teacher;Perl"
>>> line.split(";")
['James', 'Miller', 'teacher', 'Perl']
String split() Method ကေတာ္ေတာ္မ ားမ ားမာ အဆင္ေျ ပတမ္္။ ိုမိုအရဳေ ္ေ းြ တဲာ့ အလို ္ေတြ
အတြက္ေတာာ့ re module ဲက split ကိုသံိုးအရ ပမမ္္။
>>> import re
>>> metamorphoses = "OF bodies chang'd to various forms, I sing: Ye Gods,
from whom these miracles did spring, Inspire my numbers with coelestial
heat;"
>>> re.split("\W+",metamorphoses)
['OF', 'bodies', 'chang', 'd', 'to', 'various', 'forms', 'I', 'sing', 'Ye',
'Gods', 'from', 'whom', 'these', 'miracles', 'did', 'spring', 'Inspire',
'my', 'numbers', 'with', 'coelestial', 'heat', '']
Example
>>> import re
>>> lines = ["surname: Obama, prename: Barack, profession: president",
"surname: Merkel, prename: Angela, profession: chancellor"]
>>> for line in lines:
... re.split(",* *\w*: ", line)
...
['', 'Obama', 'Barack', 'president']
['', 'Merkel', 'Angela', 'chancellor']
>>>
Lambda Operator
arugment list မ
ဲ ာ comma ျ ား ားတဲာ့ list of argument ေတြ ပ ပတမ္္။ expression
ကေတာာ့ ၎ argument ေတြကိုသံိုးမမ္ာ့ arithematic expression ျ စ္ ပတမ္္။ function
ကိုပနာမည္ေ း င္အရင္လည္း variable တစ္ ို ဲကို assign လို ္ပနင္ ပတမ္္။
F = map(fahrenheit, temp)
C = map(celsius, F)
Filtering
Reducing a List
Example
>>> reduce(lambda x,y: x+y, [47,11,42,13])
113
Examples of reduce()
Introduction
List compression ဆိုတာကေတာာ့ python မာ List ေတြ ပန္တါး ိုန္႔အတြက္ သ ္အရ ္လ တဲန္႔
ပနည္းလမ္းတစ္ ိုျ စ္ ပတမ္္။
Examples
Set comprehension က list comprehension ပနဲန္႔တ ပတမ္္။ သကေတာာ့ set တစ္ ို return
ျ ပန္ေ း ပတမ္္။ set လို ္ ိုန္႔ {} ေတြသံိုး ပတမ္္။ ိုပန ျ ပနာကို ္တာေတြမ ပ င္အရင္ set
comprehension သံိုးအရ ပမမ္္။
>>> from math import sqrt
>>> n = 100
>>> sqrt_n = int(sqrt(n))
>>> no_primes = {j for i in range(2,sqrt_n) for j in range(i*2, n, i)}
>>> no_primes
{4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30,
32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55,
56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80,
81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99}
>>> primes = {i for i in range(n) if i not in no_primes}
>>> print(primes)
{0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97}
>>>
for i in range(1,50):
print i, primes(i)
Introduction
Method of Operation
Generator ကို function ေတြလို ဲ call လို ္ ပတမ္္။ သက return ျ ပန္ေ းတာကေတာာ့
iterator object ျ စ္ ပတမ္္။ ဒါအ ေတာာ့ generator code ေတြအလို ္မလို ္ေသး ပ
Iterator ေတြကိုေတာာ့ next method ပနဲာ့ေ ခ ပတမ္္။ မဆံိုး မာေတာာ့ function
လိုအလို ္လို ္ ပတမ္္။yield statement ကိုမေတြန္႔မ င္းျ စ္ ပတမ္္။
Yield ကေတာာ့ expression တစ္ ိုအရဲာ့ value ကို keyword yield ပနဲrန္႔ eturn
ျ ပန္ေ း ပတမ္္။ ဒပကေတာာ့ function ပနဲာ့တ ပတမ္.ဒပေ မမ္ာ့ pythonက yield အရဲာ့ position
ေတြ local variable ေတြကို next call အတြက္ မတ္ ားေ း ပတမ္္။ ေပနာက္တစ္ ပ call
လို ္တဲာ့ အ ပ yield statement ေပနာက္ကေပနျ ါးဆက္ျ ါး execution ဆက္လို ္ ပတမ္္။
ေပနာက္ဆံိုး အကိုပန္ျ ါးသြားတမ္ သိုန္႔ value မ ပတဲန္႔ return တစ္ ိုေတြန္႔အရင္ iterator
ျ ါးဆံိုး ျ ါျ စ္ ပတမ္္။
Python implementation
f = fibonacci()
counter = 0
for x in f:
print x,
counter += 1
if (counter > 10): break
print
Recursive Generators
abc
acb
bac
bca
cab
cba
def permutations(items):
n = len(items)
if n==0: yield []
else:
for i in range(len(items)):
for cc in permutations(items[:i]+items[i+1:]):
yield [items[i]]+cc
A Generator of Generators
Exeception ဆိုတာကေတာာ့ program တစ္ ိုကို execute လို ္တဲာ့အ ပမာ ျ စ္ေ ခလာတဲာ့ error
ေတြျ စ္ ပတမ္္။ exeception handling ဆိုတာကေတာာ့ error ေတြျ စ္ေ ခလာလ င္
အလိုအေလ ာက္ ကိုင္တြမ္ေျ အရင္းတာကိုဆိုလို ပတမ္္။
Error handling ကို error ျ စ္ေ ခတဲာ့အ ပမာအရတန္႔ဲ execution state ေတြကို မတ္သားျ ါးေတာာ့
သန္႔အတြက္ ေအရးသား ားတဲာ့ code ေတြ(exeception handler) ပနဲန္႔ေျ အရင္း ပတမ္္။ ျ စ္ေ ခလာ တဲာ့
error ေ ခမတည္ျ ါးေတာာ့ error handler ကျ င္ဆင္ေ းပနိုင္သလို သမ္း ားတဲာ့ data ေတြပနဲန္႔
ဆက္လက္လို ္ေဆာင္ပနိုင္ ပတမ္္။
Execption handling မာ python က java ပနဲန္႔တ ပတမ္္။ execption ျ စ္ပနိုင္တာ့ဲ code ကို try
block မ
ဲ ာ ား ပတမ္္။ java မာေတာာ့ exeception ေတြကို catch ပနဲာ့သံိုးေ မမ္ာ့ python
မာေတာာ့ except ပနဲန္႔သံိုး ပတမ္္။raise statement ပနဲန္႔လည္း ကိုမ္ ိုင္ execption
ေတြလို ္ပနိုင္ ပေသးတမ္္။
Example- user ကို integer number ည္ာ့ ိုင္းမမ္္။ raw_input() ကိုသံိုးအရင္input က string
ျ စ္မမ္ ဒပေႀကာင္း Integer ျ စ္ေအာင္ cast လို ္ေ းအရမမ္္။ input က integer မဟိုတ္အရင္
ValueError တက္မမ္.္။
>>> n = int(raw_input("Please enter a number: "))
Please enter a number: 23.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.5'
ဒပကို execption handling ည္ာ့ေအရးရင္
while True:
try:
n = raw_input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print "Great, you successfully entered an integer!"
ဒပဆိုအရင္ integer ေ းမ ဲ loop ကို break လို ္မမ္္။
Sample output
$ python integer_read.py
Please enter an integer: abc
No valid integer! Please try again ...
Please enter an integer: 42.0
ေပနာက္ စ မာတစ္ ိုအေပနပနဲာ့ file read လို ္ ိုန္႔ open မမ္္။file ဲက Line တစ္ေႀကာင္း read
ျ ါးေတာာ့ အဲန္႔ဒါ line ကို Integer ေျ ာင္းမမ္္။အပနည္းဆံိုး execption ႏွာစ္ ိုျ စ္ပနိုင္တမ္္။
an IOError
ValueError
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "No valid integer in line."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
IOError ကို handling လို ္တာႀကည္ာ့အရမာျ စ္ ပတမ္္။ IOError က tuple အေပနပနဲန္႔ error
number ေတြ error message string ေတြကို ိုတ္ေ း ပတမ္္။ ဒပေတြကို variable errno ပနဲာ့
strerror မ
ဲ ာ "except IOError as (errno, strerror)" လိုန္႔ assign လို ္ ာ့ဲ ပတမ္္။ မအရတဲာ့ file
တစ္ ိုကို အ က္ ပ script သံိုးျ ါး ြင္ာ့ ိုန္႔ႀကဳေးစားအရင္ ေအာက္ ပ message အရ ပမမ္္။
I/O error(2): No such file or directory
Integers.txt က readable မျ စ္အရင္ read လို ္ ိုန္႔ permission မအရအရင္ေတာာ့
I/O error(13): Permission denied
Except clause တစ္ို ကို execption တစ္ ို က္ ိုျ ါးေ း င္အရင္ tuple ေတြပနဲာ့
ပနာမည္ေ းပနိုင္ ပတမ္္။
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except (IOError, ValueError):
print "An I/O error or a ValueError occurred"
except:
print "An unexpected error occurred"
raise
sample output
bernd@venus:~/tmp$ python finally2.py
Your number: 37
There may or may not have been an exception.
bernd@venus:~/tmp$ python finally2.py
Your number: seven
You should have given either an int or a float
There may or may not have been an exception.
bernd@venus:~/tmp$ python finally2.py
Your number: 0
Infinity
There may or may not have been an exception.
bernd@venus:~/tmp$
tr…except clause မာ else clause လည္း ပပနင္ ပတမ္္။ else ကို except ေတြအားလံိုးေပနာက္မာ
ားအရ ပမမ္္။ try မာ error မတက္အရင္ else အလို ္လို ္ေ း ပမမ္္။
example
import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
text = fh.readlines()
fh.close()
except IOError:
print 'cannot open', file_name
if text:
print text[100]
ဒါစ မာ မာ commamd line argument ကေပန file name ကိုလက္ ံေ း ပတမ္္။
“exception_test.py” လိုန္႔သမ္း ားတမ္ဆို ပဆိုန္႔.္။ဒပဆိုအရင္
python exception_test.py integers.txt
ဒါလိုမလို ္ င္အရင္ "file_name = sys.argv[1]" to "file_name = 'integers.txt'"
လိုန္႔ေျ ာင္းလိုက္ ပ္။
import sys
file_name = sys.argv[1]
text = []
try:
fh = open(file_name, 'r')
except IOError:
print 'cannot open', file_name
else:
text = fh.readlines()
fh.close()
if text:
print text[100]
မတတာကေတာာ့ first case မာျ စ္ ပတမ္္။
Example:
>>> x = 5
>>> y = 3
>>> assert x < y, "x has to be smaller than y"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: x has to be smaller than y
>>>
တစ္ ိုန္႔က oop ကို modern programming paradigm တစ္ ိုလိုန္႔ င္ေ မဲာ့ ၁၉၆၀
ေလာက္ကစတမ္ ေျ ာအရ ပမမ္္။ မဆံိုး object သံိုးတဲာ့ language ကေတာာ့ simula 67 ပ္။
OOP ကိုေကာင္းတမ္ေျ ာတဲာ့သအရ ာ့ဲ သလို မေကာင္းဘးေျ ာတဲာ့သမ ားလည္း အရ ဲာ့ ပတမ္္။ OOP
C++ အရဲာ့ designer/implementer ျ စ္တာ့ဲ Alexander StepanovကOOP provides a
mathematically-limited viewpoint and called it "almost as much of a hoax as Artificial
Intelligence".လိုန္႔ေျ ာ ဲာ့ ပတမ္္။
Edsger W. Dijkstra, one of the most renown professors of Computer Science, wrote:
"... what society overwhelmingly asks for is snake oil. Of course, the snake oil has
the most impressive names - otherwise you would be selling nothing - like
"Structured Analysis and Design", "Software Engineering", "Maturity Models",
"Management Information Systems", "Integrated Project Support Environments"
"Object Orientation" and "Business Process Re-engineering" (the latter three being
known as IPSE, OO and BPR, respectively).
Encapsulation
Data Abstraction
Polymorphism
Inheritance
Object oritented program တစ္ ိုကို class ေတြေ ခမာအေျ ံ ားျ ါးေတာာ့ သပနဲန္႔တဲဆ
ြ က္
အလို ္လို ္ေပနတဲာ့ object မ ား ပအရ ပတမ္္။ ံိုမပန္ program ေတြမာေတာာ့ function ေတြ routine
ေတြပနဲန္႔ အ
ဲ လို ္လို ္ ပတမ္္။ OOP မာ object ေတြဟာ တစ္ ိုပနဲန္႔တစ္ ို message မ ားလက္ ံျ င္း္။
data မ ားတြက္ က္ေ းျ ငး္္။ တစ္ျ ား object မ ားဆါသိုန္႔ message ေ း ိုန္႔ျ င္းမ ားလို ္ေဆာင္ေ း
ႀက ပတမ္္။
Class ကိုေျ ာအရအရင္ cake တစ္ ိုလို ္ ိုန္႔လိုအ ္တာ့ဲ receipe ပနဲန္႔မစ္ႀကည္ာ့ပနင္ ပတမ္္။ cake တစ္ ို
ိုတ္ ိုန္႔အတြက္ receipe လို ပတမ္္။ receipe(class) ပနဲန္႔ cake(an instance or an object of this
Class ေတြအရဲာ့ instance ေတြ Object ေတြအရပနိုင္ ပတမ္္။ instance ဆိုတာကေတာာ့ run-time မာ
ပန္တါးလို္က္တဲာ့ class အရဲာ့ object ျ စ္ ပတမ္္။ object ေတြအရဲာ့ attribute value ေတြကိုေတာာ့ state
လိုန္႔ေ ခ ပတမ္္။ object မာ class မ
ဲ ာသတ္မတ္ ားတဲာ့ state ပနဲန္႔ behavior ပ၀င္ ပတမ္္။
အ က္မာေျ ာ ဲာ့သလို ဲ class ေတြမာလည္း attribute ေတြ properties ေတြ ပနဲန္႔ instance
ေတြအတြက္ method ေတြ ပ၀င္ ပတမ္္။ method ဆိုတာကေတာာ့ function ပ ဲ ဒပေ မမ္ာ့သက
class က ိုင္တာျ စ္ ပတမ္္။ class မ
ဲ ာသတ္မတ္ ားတာျ စ္ျ ါး instance ေတြ ပနဲာ့ class data
ေတြအတြက္အလို ္လို ္ ပတမ္္။ method ေတြကို class အရဲာ့ instance ေတြ subclass ေတြကသာ
အသံိုးျ ဳေပနိုင္ ပတမ္္။
“Account” ပနဲန္႔ “Account Holder”ဆိုျ ါး class ႏွာစ္ ိုအရမမ္္။ “Account Holder” အရဲန္႔ data မာ
Holder Surname and Prename, Adress, Profession, and Birthday စတာေတြ ပ ပမမ္္။
method ေတြကေတာာ့ "Change of Residence" and "Change of Profession"
ေတြျ စ္ ပတမ္္။ ျ ါးျ ည္ာ့စံို တဲာ့ model ေတာာ့မဟိုတ္ ပဘး္။ data ေတြ method
ေတြအမ ားႀကါးလို ပစါးမမ္္။
Encapsulation of Data
ဒါလိုကာကြမ္ ားတာေတြကို ေအရာင္အရား ိုန္႔လည္းျ စ္ပနိုင္ ပတမ္္။ c++ မာ “friends” , java ပနဲာ့
ruby မာ reflection api ,python မာ ေတာာ့ mangling ကိုသံိုးပနိုင္ ပတမ္္။
Inheritance
Class တစ္ ိုက အျ ား class ေတြကို inherit လို ္ပနိုင္ ပတမ္္။ super-class တစ္ ိုဆါကေပန class
တစ္ ို attribute ေတြ behavior ေတြ inherit လို ္ပနိုင္ ပတမ္္။ super-class ကေပန inherit
လို ္တဲာ့ class ကိုက ေတာာ့ sub-class လိုန္႔ေ ခ ပတမ္္။ super-class ကို anscestor
လိုန္႔လည္းေ ခ ပေသးတမ္္။
Definition of Methods
def balance(self):
pass
Constructor
Python မာ c++,java တိုန္႔လို explicit constructor ေတြမအရ ပဘး္။ဒပေ မမ္ာ့ __init__() method
ကေတာာ့ပနည္းပနည္းတ ပတမ္္။ သက constructor လို ္တဲာ့အလို ္ ေတာ္ေတာ္မ ားမ ား
လို ္ေ း ပတမ္္။ စ မာ. Class instance တစ္ ိုလို ္တာ့အ
ဲ ပ ၎ကို အအရင္ execute လို ္ ပတမ္္။
ပနာမည္ကလည္း construntor ပနဲာ့ဆင္ ပတမ္္။ ဒပေ မမ္ာ့ constructor လိုန္႔ေတာာ့ေ ခလိုန္႔မအရ ပဘး္။
ဘာေႀကာင္န္႔လဆ
ဲ ိုေတာာ့ __init__ ကိုေ ခတဲာ့အ ပန္ မာ instance ကလို ္ျ ါးေပနျ ါျ စ္ ပတမ္္။
ဒပေ မမ္ာ့ object initialize လို ္ ိုန္႔အတြက္ေတာာ့ __init__ method ကိုသံိုး ပတမ္္။ init ေအရးတဲာ့
ံိုစံကေတာာ့ တစ္ျ ား method ေတြေအရးသလို ပ ဲ္။
def __init__(self, holder, number, balance,credit_line=1500):
self.Holder = holder
self.Number = number
self.Balance = balance
self.CreditLine = credit_line
def balance(self):
return self.Balance
Data Encapsulation
Identifiter ကို “_” underscore character ပနဲန္႔ မစအရင္ အျ င္ကေပန အရမအသံိုးျ ဳေပနိုင္ ပတမ္္။
ဆိုလိုတာကေတာာ့ တပန္ ိုးေတြကို တ္လိုန္႔အရ ေျ ာင္းလဲလိုန္႔အရ ပတမ္္။ data ေတြကိုကာကြမ္ င္
အရင္ေတာာ့ member ေတြကို private or protected ားအရ ပမမ္္။ underscore character ႏွာစ္ ိုပနဲာ့
အစျ ဳေ ားတဲာ့ instance variable name ေတြကို class အျ င္ကေပန မသံိုးစြဲပနိုင္ ပဘး္။ direct
မအရေ မမ္ာ့လည္း private name mangling သံိုးျ ါး access သံိုးပနိုင္ ပေသးတမ္္။
ဆိုလိုတာကေတာာ့ private data __A ကို ေအာက္ ပအတိုင္းသံးပနိုင္ ပတမ္္။
instance_name._classname__A ေအာက္မာအရင္းျ ား ပတမ္္။
>>> from mangling import Mangling
>>> x = Mangling(42)
>>> x.__A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Mangling' object has no attribute '__A'
>>> x._Mangling__A
42
>>>
_name Protected Like a public member, but they shouldn't be directly accessed
from outside.
Object variable (instance variable )ေတြေတာာ့သံိုး ာ့ျဲ ါ္။ ၎ variable ေတြဟာ မတညါတာ့ဲ
object ေတြအတြက္မတညါတာ့ဲ value ေတြအရႀက ပတမ္္။eg္။ account ႏွာစ္ ိုမာဆိုအရင္ acoount
number မတပနိုင္သလို balance ေတြလည္း တ င္မတ ပလမ္ာ့မမ္္။ Object variable ေတြကို
object ေတြ class instacce ေတြစတဲန္႔ ဆိုင္အရာဆိုင္အရာက ိုင္ဆိုင္ႀက ပတမ္္။ object
ေတြအရဲာ့ကိုမ္ ိုင္ variable ေတြျ စ္ ပတမ္္။ object တစ္ ိုျ င္းစါ အတြက္ ပန္တါးေ း ားတာ ျ
ျ စ္တာေႀကာင္ာ့ non-static or dynamic variable or members လိုန္႔ေ ခႀက ပတမ္္။
Class variable ကေတာာ့ object အားလံိုးကမ ေ၀သံိုးစြဲႀက ပတမ္္။ သတိုန္႔ကိုေတာာ့ မည္သည္ာ့
object ကေပနမဆို ေျ ာင္းလဲမေတြလို ္ပနိုင္ ပတမ္္။ object အားလံိုးအတြက္ တစ္ ို ဲအရတာေႀကာင္ာ့
အျ ား object ေတြအတြက္လည္းေျ ာင္းလဲ ပတမ္္။
Static variable အတြက္ example အေပနပနဲန္႔္။ account စိုစိုေ ပင္း တြက္မမ္ာ့ counter variable
တစ္ ိုလို ္ ပမမ္္။ ဒပကို class အရဲာ့ေအာက္မာ တစ္ ပ ဲျ ဳေလို ္သြား ပမမ္္။ constructor
ကိုေ ခတိုင္း variable ကို တိုးသြား ပမမ္္။ account အရဲာ့ object ကို က္မမ္ဆိုအရင္
ေလ ာာ့သြား ပမမ္္။
class Account(object):
counter = 0
def __init__(self, holder, number, balance,credit_line=1500):
Account.counter += 1
self.__Holder = holder
self.__Number = number
self.__Balance = balance
self.__CreditLine = credit_line
def __del__(self):
Account.counter -= 1
Interaction session မာ ျ သြား ပမမ္္။
>>> from Account import Account
>>> Account.counter
0
>>> a1 = Account("Homer Simpson", 2893002, 2325.21)
>>> Account.counter
1
>>> a2 = Account("Fred Flintstone", 2894117, 755.32)
>>> Account.counter
2
>>> a3 = a2
>>> Account.counter
2
>>> a4 = Account("Bill Gates", 2895007, 5234.32)
>>> Account.counter
3
Account class ကေပန inherit လို ္ပနိုင္တာ့ဲ Counter class တစ္ ိုလို ္ျ ါး inheritance
ကိုစမ္းႀကည္ာ့ ပမမ္္။ ဒပဆိုအရင္ account သိုန္႔ အျ ား class ေတြ မ
ဲ ာ count
လို ္စအရာမလိုေတာာ့ ပဘး္။ eg member or employee
def __init__(self):
type(self).number += 1
def __del__(self):
type(self).number -= 1
class Account(Counter):
def __init__(self,
account_holder,
account_number,
balance,
account_current=1500):
Counter.__init__(self)
Multiple Inheritance
Class တစ္ ိုသည္ inherit လို ္ျ င္းကို class တစ္ ို က္ ို လို ္ေဆာင္ပနိုင္ ပတမ္္။ ဒပကို
multiple inheritance လိုန္႔ေ ခ ပတမ္္။ ေအရးသားတာကေတာာ့လြမ္ ပတမ္္။ super-class
အားလံိုးကို class ေပနာက္က () မ
ဲ ာ comma ံျ ါးေအရးသားပနိုင္ ပတမ္္။
class NN (class1, class2, class3 ...):
This class inherits from class1, class2, and so on.
Introduction
ဒါအတြက္ base class ႏွာစ္ ိုလို ္ ပမမ္္။ clock အတြက္အရမ္ calendar အတြက္အရမ္ျ စ္ ပတမ္္။ ဒါ
ႏွာစ္ ိုအေ ခမာ အေျ ံျ ါးေတာာ့(inherit) CalendarClock ဆိုတဲာ့ class ျ ဳေလို ္ ား ပတမ္္။
def tick(self):
""" Time will be advanced by one second """
if self.__seconds == 59:
self.__seconds = 0
if (self.__minutes == 59):
self.__minutes = 0
self.__hours = 0 if self.__hours==23 else self.__hours+1
else:
self.__minutes += 1;
else:
self.__seconds += 1;
def display(self):
print("%d:%d:%d" % (self.__hours, self.__minutes, self.__seconds))
def __str__(self):
return "%2d:%2d:%2d" % (self.__hours, self.__minutes,
self.__seconds)
x = Clock()
print(x)
for i in xrange(10000):
x.tick()
print(x)
def leapyear(self,y):
if y % 4:
# not a leap year
return 0;
else:
if y % 100:
return 1;
else:
if y % 400:
return 0
else:
return 1;
def get():
return (self, self.__day, self.__month, self.__year)
def advance(self):
months = Calendar.months
max_days = months[self.__month-1]
if self.__month == 2:
max_days += self.leapyear(self.__year)
if self.__day == max_days:
self.__day = 1
if (self.__month == 12):
self.__month = 1
self.__year += 1
else:
self.__month += 1
else:
self.__day += 1
def __str__(self):
return str(self.__day)+"/"+ str(self.__month)+ "/"+ str(self.__year)
if __name__ == "__main__":
x = Calendar()
print(x)
x.advance()
print(x)
def __str__(self):
return Calendar.__str__(self) + ", " + Clock.__str__(self)
if __name__ == "__main__":
x = CalendarClock(24,12,57)
print(x)
for i in range(1000):
x.tick()
for i in range(1000):
x.advance()
print(x)
Class တစ္ ိုကို design လို ္အရာမာ slot ကိုသံိုးျ ါး attribute dynamic creation ကိုကာကြမ္
ပနိုင္ ပတမ္္။ slot လို ္ ိုန္႔အတြက္ “__slots__” ဆိုတဲာ့ list တစ္ ိုလို ္ေ းအရ ပမမ္္။ list မ
ဲ ာ
__slots__ = ['val']
x = S(42)
print(x.val)
program ကို run လိုက္မမ္ဆိုအရင္ dynamic attribute ေတြလို ္မအရတာ ေတြန္႔ ပလမ္ာ့မမ္္။ 42
Traceback (most recent call last):
File "slots_ex.py", line 12, in <module>
x.new = "not possible"
AttributeError: 'S' object has no attribute 'new'
Slot ေတြဟာ object ေတြကspace comsuption လို ္တာကို ကာကြမ္ေ းတမ္လိုန္႔ေျ ာ ဲာ့
ပတမ္္။ python 3.3 ေပနာက္မာေတာာ့ သ ္ျ ါးအသံိုးမ၀င္ေတာာ့ ပဘး္။ python 3.3 မာ object
ေတြကို သမ္း ိုန္႔အတြက္ Key-Sharing dictionary ေတြကိုသံိုး ပတမ္္။ instance ေတြအရဲာ့ attribute
ေတြဟာ တစ္ ိုပနဲာ့ တစ္ ို မ ေ၀သံိုးစြဲလာပနိုင္ ပတမ္္။ ဆိုလိုတာက key သမ္း ားတဲာ့ အ ိုင္းပနဲာ့
သက္ဆိုင္အရာ hash ေတြကိုျ စ္ ပတမ္္။ ဒပေႀကာင္ာ့ non-builtin type instance ေတြအမ ား ႀကါး
တည္ေဆာက္တန္႔ဲ program ေတြမာ memory consumption ကိုေလ ာာ့ ေ း ပတမ္္။
Python2 မာအေအရာ့ ပန္းေတြမာေျ ာ ဲသလို ဲ အရို ္ေ ြးပနိုင္တာတစ္ ိုအရ ပတမ္္။ The coexistence
of old-style and new-style classes.
"New-style classes were introduced in Python 2.2 to unify classes and types. A new-
style class neither more nor less than a user-defined type. If x is an instance of a
new-style class, then type(x) is the same as x.class."
# new-style class
class A(object):
pass
class B(A):
pass
a = A()
b = B()
ဒပႀကာင္ာ့ class ေတြဟာ type ဆိုတဲာ့ class ကေပန ပန္တါးတာျ စ္ ပတမ္္။ puthon 3 မာ ေတာာ့
class ပနဲန္႔ type အတတ ပ ဲ္။
One argument အစာ းtype ကို parameter 3 ိုပနဲန္႔ အသံိုးျ ဳေပနိုင္ ပတမ္္။
type(classname, superclasses, attributes_dict)
class Philosopher2:
def the_answer(self, *args):
return 42
class Philosopher3:
def the_answer(self, *args):
return 42
plato = Philosopher1()
print(plato.the_answer())
kant = Philosopher2()
# let's see what Kant has to say :-)
print(kant.the_answer())
42
42
“the_answer” method ကို ြား ားတာေတြေတြန္႔မာျ စ္ ပတမ္္။ error ျ စ္ပနိုင္လို maintain
လို ္ ိုန္႔လည္း က္ ပတမ္္။
သ ာ့သ
ဲ ေလာက္ပနာ့ဲ redundant code ေတြကိုေျ အရင္းမမ္ဆိုအရင္ေတာာ့ “the_answer” method
ပ၀င္တာ့ဲ Base class တစ္ ိုတည္ေဆာက္မာ ပ ္။ျ ါးေတာာ့ Philosoper class ေတြက inherit
လို ္မာျ စ္ ပတမ္္။
class Answers:
def the_answer(self, *args):
return 42
class Philosopher1(Answers):
pass
class Philosopher2(Answers):
pass
class Philosopher3(Answers):
pass
plato = Philosopher1()
print(plato.the_answer())
kant = Philosopher2()
# let's see what Kant has to say :-)
class Philosopher1:
pass
if required:
Philosopher1.the_answer = the_answer
class Philosopher2:
pass
if required:
Philosopher2.the_answer = the_answer
class Philosopher3:
pass
if required:
Philosopher3.the_answer = the_answer
plato = Philosopher1()
kant = Philosopher2()
# let's see what Plato and Kant have to say :-)
if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers")
Do you need the answer? (y/n): y
42
42
ဒပက ဒါျ ပနာအတြက္ ေျ အရင္း က္တစ္ ိုဆိုေ မဲာ့ မေကာင္းတာေတြအရ ပေသးတမ္္။
ဘာလိုလဆ
ဲ ိုေတာာ့ class တိုင္းကို code အတတေတြ ည္ာ့အရမာျ စ္ျ ါး ဒပကေ
ို မန္႔ပနိုင္ ပေသးတမ္္။
ဒပာ့အျ င္ method ေတြအမ ားႀကးဆိုအရင္ အရို ္ေ းြပနိုင္ ပေသးတမ္္။
ဒပကို ိုေကာင္းေအာင္း manager function တစ္ ိုလို ္ျ ါး redundant code ေတြ မ္ပနိုင္ ပတမ္္။
manager function ကိုသံိုးျ းေတာာ့ calss ကို conditionally augument လို ္မာ ပ္။
# the following variable would be set as the result of a runtime
calculation:
# manager function
def augment_answer(cls):
if required:
cls.the_answer = the_answer
class Philosopher1:
pass
augment_answer(Philosopher1)
class Philosopher2:
pass
augment_answer(Philosopher2)
class Philosopher3:
pass
augment_answer(Philosopher3)
plato = Philosopher1()
kant = Philosopher2()
# let's see what Plato and Kant have to say :-)
if required:
print(kant.the_answer())
print(plato.the_answer())
else:
print("The silence of the philosphers")
Do you need the answer? (y/n): y
42
42
ျ ပနာကိုေျ အရင္း န္႔အ
ို သံိုး၀င္ေ မမ္ာ့ကၽြပန္ေတာ္ တိုန္႔က manage fuction ျ စ္တာ့ဲ
“augument_answer” ကို ေ ခ ိုန္႔ေမန္႔ပနိုင္ ပေသးတမ္္။ code ေတြကို အလိုအေလ ာက္ execute
လို ္သင္ာ့ ပတမ္္။ class definition ျ ါးလ င္ အလိုအေလ ာက္ အလို ္လို ္မမ္ာ့ code အ ဳေလို
ေပန ပတမ္္။
# the following variable would be set as the result of a runtime
calculation:
x = input("Do you need the answer? (y/n): ")
if x=="y":
required = True
else:
required = False
def augment_answer(cls):
if required:
cls.the_answer = the_answer
# we have to return the class now:
@augment_answer
class Philosopher1:
pass
@augment_answer
class Philosopher2:
pass
@augment_answer
class Philosopher3:
pass
plato = Philosopher1()
kant = Philosopher2()
Metaclasses
Metaclass ေတြဆိုတာကေတာာ့ class တစ္ ို ဲျ စ္ျ ါးေတာာ့ ၎ အရဲာ့ object ေတြကလည္း class
ေတြ ဲျ စ္ ပတမ္္။ ံိုမပန္ classs တစ္ို ိုက class object behavior ေတြကိုသတ္မတ္သလို ဲ
,metaclass ကလည္း class ေတြပနဲန္႔ ၎ အရဲာ့ object ေတြအတြက္ကို behavior
ေတြသတ္မတ္ေ း ပတမ္္။
Defining Metaclasses
Metaclass ကအျ ား class ပနဲာ့တေ မမ္ာ့ အျ ား class ေတြက “type” ကေပန inherit
လို ္ ားတာျ စ္ ပတမ္္။ ေပနာက္မတတာက metaclass ကိုသံိုး ားတဲာ့ class statement
ေတြဆံိုးအရင္ metaclass ေတြကို အလိုအေလ ာက္ ေ ခေ း ပတမ္္။ metaclas မသံိုး ားအရင္
type() class ကိုေ ခတာျ စ္ျ ါး သံိုး ားအရင္ေတာာ့ type အစား metaclass ကိုေ ခတာျ စ္ ပတမ္္။
class EssentialAnswers(type):
class Philosopher1(metaclass=EssentialAnswers):
pass
class Philosopher2(metaclass=EssentialAnswers):
pass
class Philosopher3(metaclass=EssentialAnswers):
pass
plato = Philosopher1()
print(plato.the_answer())
kant = Philosopher2()
# let's see what Kant has to say :-)
print(kant.the_answer())
Do you need the answer? (y/n): y
42
42
Class definition ျ ါးအရင္ pyton ကေအာက္ ပ function ကိုေ ခ ပတမ္္။
type(classname, superclasses, attributes_dict)
metaclass ကို header အေပနပနဲာ့ေျ ာ ားအရင္ ဒပကျ ပနာမဟိုတ္ ပဘး္။ ိုပန example မာ
ဒါလိုလို ္ ားတာျ စ္ ပတမ္္။ Philosopher1, Philosopher2 and Philosopher3ေတြကို
metaclass ျ စ္တာ့ဲ EssentialAnswers ပနဲန္႔ တ္ ား ပတမ္္။ဒပေႀကာင္ာ့ type အစား
EssentialAnswer ကိုေ ခတာျ စ္ ပတမ္္။
EssentialAnswer(classname, superclasses, attributes_dict)
အတအက ေျ ာအရအရင္ call လို ္တဲာ့ argument ေတြကိုေအာက္ ပတပန္ ိုးေတြျ စ္ ပတမ္္။
Singleton pattern ဆိုတာကေတာာ့ design pattern တစ္ ိုျ စ္ျ ါးေတာာ့ class တစ္ ိုအတြက္ ကို
object တစ္ ိုလိုကပန္သတ္ ား ပတမ္္။ object တစ္ ို ဲလိုအ ္တာ့အ
ဲ ပသံိုး ပတမ္္။
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton,
cls).__call__(*args, **kwargs)
return cls._instances[cls]
class SingletonClass(metaclass=Singleton):
pass
class RegularClass():
pass
x = SingletonClass()
y = SingletonClass()
print(x == y)
x = RegularClass()
y = RegularClass()
print(x == y)
True
False
Creating Singletons using Metaclasses
class SingletonClass(Singleton):
pass
class RegularClass():
pass
x = SingletonClass()
y = SingletonClass()
print(x == y)
x = RegularClass()
y = RegularClass()
print(x == y)
True
False
Introduction
ဒါအ ပန္းမာေတာာ့ meatclass use case ကို စ မာပနဲာ့ေျ ာသြားမာျ စ္ ပတမ္္။ metaclass တစ္ ိုကို
တည္ေဆာက္မမ္ ၎ ျ ါးေတာာ့ subclass အရဲာ့ method ေတြကို decorate လို ္မာျ စ္ ပတမ္္။
decorator ကေပန return ျ ပန္လာတဲာ့ decorated function ေတြက subclass အရဲာ့ method ေတြကို
ဘမ္ႏွာစ္ႀကမ္ call လို ္လဲဆိုတာကို ေအရတြက္ပနိုင္ ပတမ္္။
Preliminary Remarks
ျ ပနာကို မေျ အရင္း င္ class attribute ေတြကို ဘမ္လို access လို ္လဲျ ပန္ႀကည္ာ့အရေအာင္္။
list class ပနဲာ့ျ ပမမ္္။ class တစ္ ိုအရဲာ့ non-private attribute list
ကိုေအာက္ ပအတိုင္းအရပနိုင္ ပတမ္္။
import random
cls = "random" # name of the class as a string
all_attributes = [x for x in dir(eval(cls)) if not x.startswith("__") ]
print(all_attributes)
ဒပဆိုေအာက္ ပအတိုင္းအရ ပမမ္္။
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence',
'_Set', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi',
'_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator',
'_urandom', '_warn', 'betavariate', 'choice', 'expovariate',
'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate',
'normalvariate', 'paretovariate', 'randint', 'random', 'randrange',
'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform',
'vonmisesvariate', 'weibullvariate']
print(f.calls)
ေအာက္ ပအတိုင္း ိုတ္ေ း ပလမ္န္႔မမ္္။
0
10
print(f.calls)
def f():
pass
f = call_counter(f)
print(f.calls)
for _ in range(10):
f()
print(f.calls)
@staticmethod
def call_counter(func):
""" Decorator for counting the number of function
or method calls to the function or method func
"""
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
helper.__name__= func.__name__
return helper
class A(metaclass=FuncCallCounter):
def foo(self):
pass
Abstract class ေတြကေတာာ့ abstract method မ ား ပ၀င္တာ့ဲ class ေတြျ စ္ ပတမ္္။ abstract
method ေတြကေတာာ့(declare) ေႀကျငာ ားေ မမ္ာ့ implement
မလို ္အရေသးတာေတြျ စ္ ပတမ္္။ abastract class ေတြကို instantiate မလို ္တာျ စ္ပနိုင္သလို
subclass ေတြအေပနပနဲန္႔ abastrct method ေတြကို implement လို ္ေ း န္႔လ
ို ိုအ ္ ပတမ္္။ python
အရဲာ့ abstract class တစ္ ိုအရဲာ့ subclass ကေတာာ့ paret class အရဲာ့ abstract method ေတြကို
implement လို ္စအရာမလို ပဘး္။
Example ႀကည္ာ့အရေအာင္
class AbstractClass:
def do_something(self):
pass
class B(AbstractClass):
pass
a = AbstractClass()
b = B()
ဒပကိုႀကည္ာ့အရင္ abastract class မဟိုတ္တာကိုေတြန္႔ ပမမ္္။ ဘာလိုာ့လဆ
ဲ ိုေတာာ့
ေအာက္မာ abc module ကိုသံိုးျ ါးေတာာ့ abtract base class တစ္ ိုတည္ေဆာက္ ား ပတမ္္။
from abc import ABC, abstractmethod
class AbstractClassExample(ABC):
@abstractmethod
def do_something(self):
pass
အ ို abstract class ကိုသံိုး ိုန္႔ subclass လို ္မမ္္။ do_something method ကို implement
လို ္ ိုန္႔လေ မမ္ာ့ မလို ္အရေသးတာေတြန္႔မျ စ္ ပတမ္္။ဘာေႀကာင္ာ့လဲဆိုေတာာ့ ၎ method ကို
“abstractmethod” ဆိုတဲာ့ decorator ပနဲန္႔ docorate လို ္ ားလိုန္႔ျ စ္ ပတမ္္။DoAdd42 ကို
instantiate လို ္မအရ ပဘးဆိုတာ့ဲ exception တက္ ပလမ္ာ့မမ္္။
class DoMul42(AbstractClassExample):
def do_something(self):
return self.value * 42
x = DoAdd42(10)
y = DoMul42(10)
print(x.do_something())
print(y.do_something())
52
420
Abstract class ကေပန derived လို ္ ားတဲာ့ class ကို instantiate လို ္မမ္ဆိုအရင္ abstract
method အားလံိုးကို overridden လို ္ ားမအရ ပမမ္္။
class AbstractClassExample(ABC):
@abstractmethod
def do_something(self):
print("Some implementation!")
class AnotherSubclass(AbstractClassExample):
def do_something(self):
super().do_something()
x = AnotherSubclass()
x.do_something()
Some implementation!
The enrichment from AnotherSubclass