Professional Documents
Culture Documents
Python For A Real Programer
Python For A Real Programer
Python For A Real Programer
of Contents
1. Happy To Write the Book
2. Basic - Preparation
3. Basic - Ediotr
4. start -
5. Python
6. ipython
7. Play -
8. setup.py
OO
Developer
Architect
Operation
Package Manager
Release Manager
Quality Assurance
Test Development
tim@ubuntu:~$ vim
The program 'vim' can be found in the following packages:
* vim
* vim-gnome
* vim-tiny
* vim-athena
* vim-gtk
* vim-nox
Try: sudo apt-get install <selected package>
google,
vim ubuntu vim, ubuntu
terminal vim
ubutntu apt-get, apt-cache
apt-cache search
python shell
u'\u4e2d\u6587' unicode
pip python
ubuntu apt-get
Python
Python pip.
uniout.
,
successfully
sudo Permission denied.
root
.local/lib/python2.7/site-packages/
>>> exit()
python shell
apt-get, apt-cache,
Python Python
Virtual Environment
python virtualenv.
virtualenv
virtualenv venv
virtualenv:
source venv/bin/activate
deactivate
virtualenv
virtualenv
virtualenv
Python
: VIM, SublimeText3
IDE: Eclipse + Pydev, PyCharm
IDE
IDE
)
IDE
IDE
vim test.py
i, insert mode.
python test.py
vim ~/.vimrc
:set tabstop=4
:set shiftwidth=4
:set expandtab
test.py
vim
PyCharm
vim pycharm
PyCharm vim plugin,
Project, first.py first.py
pycharm key enter, pycharm
a = list()
a.append(10)
a.append(3)
a.append(9)
print a
a.sort()
print a
Run
10, 3, 9
pycharm
list() listx()
a.append b.appedn
append
pigg = 10
pycharm
start -
Python
Don't Repeat Yourself ),
numbers = list()
numbers.append(10)
numbers.append(3)
numbers.append(9)
print numbers # [10, 3, 9]
numbers.sort()
print numbers # [3, 9, 10]
class
def
class
class Button:
'nothing here is only comment'
button = Button()
class Button:
def click(self):
print "I am clicked"
a = Button()
a.click() # I am clicked
class Button:
def click(self):
print "{0} is clicked".format(self.name)
powerup_button = Button()
powerup_button.name = 'power up'
powerup_button.click() # power up is clicked
powerdown_button = Button()
powerdown_button.name = 'power down'
powerdown_button.click() # power down is clicked
class Button:
def __init__(self, name):
self.name = name
def click(self):
print "{0} is clicked".format(self.name)
mute = Button('mute')
mute.click() # mute is clicked
PowerPoint ppt
class
class Button(object):
def __init__(self, name):
self.name = name
def click(self):
print "{0} is clicked".format(self.name)
class TV(object):
def __init__(self):
self.mute = Button('mute')
self.power = Button('power')
tv = TV()
tv.mute.click() # mute is clicked
tv.power.click() # power is clicked
Reference
Django Girl
Python
ipython ,
bpython dreampy python console
Python Shell,
a = 10
a
10 a 10
1+1
a * 2
a ** 3
a**0.5
a = "tim"
a.upper()
list
a = ['1','2','3']
a
a = ['1','2','3']
b = list('123')
a == b
Recursion
def fib(order):
if order < 2:
return order
else:
return fib(order-1) + fib(order-2)
for i in range(10):
print fib(i)
#0
#1
#1
#2
#3
#5
#8
#13
#21
#34
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2)
def anonymous(x):
return x**2 + 1
ipython
IDE ipython
In [1]: a = 10
In [2]: print a
10
ipython shell,
In [6]: random.choice?
Type: instancemethod
String form: <bound method Random.choice of <random.Random object at 0x7f8c8107ba20>>
File: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py
Definition: random.choice(self, seq)
Docstring: Choose a random element from a non-empty sequence.
function ?
??
In [48]: random.seed??
Type: instancemethod
String form: <bound method Random.seed of <random.Random object at 0x7f8c8107ba20>>
File: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py
Definition: random.seed(self, a=None)
Source:
def seed(self, a=None):
"""Initialize internal state from hashable object.
None or no argument seeds from current time or from an operating
! ipython
In [11]: !ls
README.md _book basic_ediotr imgs.png play_- start_SUMMARY.md basic imgs.graffle ipython python
In [13]: !wc ~/.vimrc
7 17 103 /Users/tim/.vimrc
In [14]: a = !cat ~/.vimrc
In [15]: a
Out[15]:
['syntax on',
'set bg=dark',
':set tabstop=4',
':set shiftwidth=4',
':set expandtab',
'ab utf8 # -*- coding: utf-8 -*-',
'']
In [16]: !nslookup www.google.com
Server: 168.95.1.1
Address: 168.95.1.1#53
Non-authoritative answer:
Name: www.google.com
Address: 74.125.203.99
Name: www.google.com
Address: 74.125.203.147
Name: www.google.com
Address: 74.125.203.105
Name: www.google.com
Address: 74.125.203.103
Name: www.google.com
Address: 74.125.203.104
Name: www.google.com
Address: 74.125.203.106
variable interpolation
list
ipython open
OO
import Tkinter.
try:
import Tkinter
except ImportError as e:
import tkinter as Tkinter
Tkinter
1. Python
2. Tk
Tcl/Tk
?
wxWIdget, pyQT, jython
.....
TK (Window Manager)
GUI
:
wm = Tkinter.Tk()
wm.title("")
Tkinter tutorial
. (e.g.)
wm1 = Tkinter.Tk()
wm2 = Tkinter.Tk()
wm1.title("1")
wm2.title("2")
Tk() GUI
wm1.lift()
wm2.lift()
Code
: ipython
title title ? ipython
wm1.title?
In [3]: wm.title?
Type: method
String form: <bound method Tk.wm_title of <Tkinter.Tk object at 0x10ce855d0>>
File: /usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3/lib/python3.
Definition: wm.title(self, string=None)
Docstring: Set the title of this widget.
Tk ( Widget )
Button
:
b = Tkinter.Button(wm1, text='')
b.grid()
Tk
b['width']
b['width'] = 100
100
Tk (widget)
Tkinter ( widget ) , ,
b.config(width=100)
b.configure(width=15)
...
TK ?
Tkinter.Button?
Type: type
String form: <class 'Tkinter.Button'>
File: /usr/local/Cellar/python3/3.3.2/Frameworks/Python.framework/Versions/3.3
Init definition: Tkinter.Button(self, master=None, cnf={}, **kw)
Docstring: Button widget.
Init docstring:
Construct a button widget with the parent MASTER.
STANDARD OPTIONS
activebackground, activeforeground, anchor,
background, bitmap, borderwidth, cursor,
disabledforeground, font, foreground
highlightbackground, highlightcolor,
highlightthickness, image, justify,
padx, pady, relief, repeatdelay,
repeatinterval, takefocus, text,
textvariable, underline, wraplength
WIDGET-SPECIFIC OPTIONS
command, compound, default, height,
overrelief, state, width
?
command, command
width
justify
state
highlightbackground
text
Google ipython
Command
def my_command():
print("pressed")
b['command'] = my_command # b is a button instance
Command
print("pressed") 'pressed'
Grid Layout
!
root = Tkinter.Tk()
button1 = Tkinter.Button(root, text="(0,0)")
button1.grid(row=0, column=0)
button2 = Tkinter.Button(root, text="(1,1)")
button2.grid(row=1, column=1)
root.mainloop()
Widget
: Layout ?
try:
import Tkinter
except ImportError as e:
import tkinter as Tkinter
root = Tkinter.Tk()
for row in range(10):
for col in range(10):
button = Tkinter.Button(root, text="B")
button.grid(row=row, column=col)
root.mainloop()
Callback
try:
import Tkinter
except ImportError as e:
import tkinter as Tkinter
root = Tkinter.Tk()
class ButtonCommand:
def __init__(self, x,y):
self.x = x
self.y = y
def on_click(self):
print( "%d %d" % (self.x, self.y))
for row in range(10):
for col in range(10):
try:
import Tkinter
except ImportError as e:
import tkinter as Tkinter
root = Tkinter.Tk()
class CB(Tkinter.Button):
def __init__(self, master=None, cnf={}, row=0, col=0, **kw):
## Python 2
Tkinter.Button.__init__(self, master, cnf, **kw)
## Python 3
#super(CB, self).__init__(master, cnf, **kw )
self.__row = row
self.__col = col
self['command'] = self.print_name
def print_name(self):
print("(%d,%d)"%(self.__row, self.__col))
! !
1.
2.
GUI
One Way Data Flow
Model Your Thought
UI
Python
? ?
Button
(()Dictionary):
a = {}
a[10] = 100
a['the coolest language'] = 'python'
print(a) # {10: 100, 'the coolest language': 'python'}
tuple key
Button
try:
import Tkinter
except ImportError as e:
import tkinter as Tkinter
class BombButton(Tkinter.Button):
def __init__(self, master=None, *args, **kwarg):
#python2
Tkinter.Button.__init__(self, master, *args, **kwarg)
#python3
#super(BombButton, self).__init__(master, *args, **kwarg)
self['text'] = "xxx"
a = BombButton()
a.grid()
a.mainloop()
init .
try:
import Tkinter
except ImportError as e:
import tkinter as Tkinter
LAYOUT = {
(0, 0): 0, (0, 1): 0, (0, 2): 0,
(1, 0): 1, (1, 1): 0, (1, 2): 0,
class BombButton(Tkinter.Button):
def __init__(self, master=None, has_bomb=0, bomb_number=0, x=0,y=0,
handle_open_button=lambda x:x, *args, **kwarg):
Tkinter.Button.__init__(self, master, *args, **kwarg)
# super(BombButton, self).__init__(master, *args, **kwarg)
self['command'] = self.on_click
self.has_bomb = has_bomb
self.x = x
self.y = y
self.handle_open_button = handle_open_button
self.bomb_number = bomb_number
self.navigated = False
def on_click(self):
if self.navigated:
return
self.navigated = True
if self.has_bomb:
self['text'] = 'X'
return
self['text'] = str(self.bomb_number)
self.handle_open_button(self)
class Application(Tkinter.Tk):
@staticmethod
def __get_sibling_coordination(x,y):
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
if dx == 0 and dy == 0:
continue
if (x+dx,y+dy) in LAYOUT.keys():
yield x+dx, y+dy
def __init__(self, spaces, *args, **kwarg):
# python2
Tkinter.Tk.__init__(self, *args, **kwarg)
# python3
# super(Application, self).__init__(*args, **kwarg)
self.buttons = {}
self.spaces = spaces
for row_index, col_index in LAYOUT.keys():
has_bomb = LAYOUT[row_index, col_index]
bomb_number = GAME_NUMBERS[row_index, col_index]
b = BombButton(self, x=row_index,
y=col_index,
has_bomb=has_bomb,
bomb_number=bomb_number,
handle_open_button=self.handle_open_button)
b.grid(row=row_index, column=col_index)
self.buttons[row_index, col_index] = b
def handle_open_button(self, button):
self.spaces -= 1
if self.spaces == 0:
print('success')
if button.bomb_number == 0:
for sx, sy in Application.__get_sibling_coordination(button.x, button.y):
sibling = self.buttons[sx, sy]
sibling.on_click()
if __name__ == '__main__':
app = Application(spaces=TOTAL_SPACES)
app.mainloop()
Python
1.
2.
3.
mkdir /tmp/sample
cd /tmp/sample
vim setup.py
setup.py
# setup.py
#!/usr/bin/env python
from distutils.core import setup
setup(name='SetupSample',
version='1.0',
description='Example',
author='Tim Hsu',
author_email='tim.yellow@gmail.com',
url='https://www.python.org/sigs/distutils-sig/',
)
python setup.py
... ...
https://docs.python.org/2/distutils/setupscript.html
Python
vim hi.py
hi.py
def say_hi():
print "hi"
setup.py ()
setup(name='SetupSample',
version='1.0',
description='Example',
author='Tim Hsu',
author_email='tim.yellow@gmail.com',
url='https://www.python.org/sigs/distutils-sig/',
py_modules = ['hi'], ##
)
In [3]: import hi
In [4]: hi.say_hi
Out[4]: <function hi.say_hi>
In [5]: hi.say_hi()
hi
Scripts
Terminal cat touch ls
cat2 ( .py)
#!/usr/bin/env python
print "meow~"
#!/usr/bin/env python
from distutils.core import setup
setup(name='SetupSample',
version='1.0',
description='Example',
author='Tim Hsu',
author_email='tim.yellow@gmail.com',
url='https://www.python.org/sigs/distutils-sig/',
py_modules = ['hi'],
## below are some magic
scripts=['cat2', ],
)
cat2
cat2
githib butbucket
github Repository,
github
PyPi Repository, github