Python For A Real Programer

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Table

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

BETA Version of the book.

OO

Developer
Architect
Operation
Package Manager
Release Manager
Quality Assurance
Test Development

ubutntu vim, terminal vim,

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

sudo apt-get install vim

terminal vim
ubutntu apt-get, apt-cache

apt-cache search

canonical ubuntu ubuntu

python shell

timdeMacBook-Pro:python-for-a-real-programer tim$ python


Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = u''
>>> a
u'\u4e2d\u6587'
>>>

u'\u4e2d\u6587' unicode

python uniout, python shell


apt-cache uniout
uniout uniout

sudo pip install uniout

pip python

sudo apt-get install python-pip

ubuntu apt-get

Python
Python pip.

uniout.
,

timdeMacBook-Pro:python-for-a-real-programer tim$ sudo pip install uniout


Downloading/unpacking uniout
Downloading uniout-0.3.7.tar.gz
Running setup.py egg_info for package uniout
warning: no previously-included files matching '*.pyc' found anywhere in distribution
Installing collected packages: uniout
Running setup.py install for uniout
warning: no previously-included files matching '*.pyc' found anywhere in distribution
Successfully installed uniout
Cleaning up...

successfully
sudo Permission denied.

error: /Library/Python/2.7/site-packages/_uniout.py: Permission denied


---------------------------------------Cleaning up...

Command /usr/bin/python -c "import setuptools;__file__='/private/var/folders/7r/0m7j9n750xn_hfh73nly7


Storing complete log in /Users/tim/Library/Logs/pip.log

root
.local/lib/python2.7/site-packages/

pip install --user uniout

uniout, Python shell.

>>> exit()

python shell

Python 2.7.6 (default, Sep 9 2014, 15:04:36)


[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import uniout
>>> a = u''
>>> a
u''

apt-get, apt-cache,
Python Python

Virtual Environment

python virtualenv.

sudo pip install virtualenv

ubuntu python ubuntu


pip ubuntu

virtualenv

virtualenv venv

virtualenv:

source venv/bin/activate

virtualenv, terminal virtualenv bash shell

deactivate

virtualenv

virtualenv
virtualenv

/tmp/ virtualenv virtualenv pycuber


virtualenv python shell, pycuber


Python
: VIM, SublimeText3
IDE: Eclipse + Pydev, PyCharm

IDE
IDE

)
IDE
IDE

VIM Quick Tips


vim
:

vim test.py

vim vim insert mode normal Mode.


normal mode, ,

i, insert mode.

# -*- coding: utf-8 -*import random


possible = [ u'', u'', u'']
print random.choice(possible)

normale mode ( esc) ZZ ()


bash shell :

python test.py

vim vim python

vim ~/.vimrc

.vimrc insert mode,


normal model ZZ

: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

Python: Script Language


Python 2.7
Python is an easy to learn, powerful programming language. It has efficient high-level data
structures and a simple but effective approach to object-oriented programming. Pythons elegant
syntax and dynamic typing, together with its interpreted nature, make it an ideal language for
scripting and rapid application development in many areas on most platforms.
Object Oriented

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]

list() list numbers


numbers method list append method. list
list sort method. numbers .

class
def
class

class Button:
'nothing here is only comment'
button = Button()

(class) Button, button = 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

Button('mute') instance , __init__ ,


instance, 'mute'

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,

pip install ipython

command line ipython

Python 2.7.6 (default, Sep 9 2014, 15:04:36)


Type "copyright", "credits" or "license" for more information.
IPython 2.3.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:

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

"tim" [1, 2, 3] list


:

a = ['1','2','3']
b = list('123')
a == b

tutorial, Django Girls Taipei

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)

C(n,r) = C(n-1,r-1) + C( n-1, r)


C(n,n) = 1
C(n,1) = n
C(n,r) = 1 if r > n
Combination, n r

def anonymous(x):
return x**2 + 1

def integrate(fun, start, end):


step = 0.1
intercept = start
area = 0
while intercept < end:
intercept += step
''' your work here '''
return area
print(integrate(anonymous, 0, 10))

ipython
IDE ipython

In [1]: a = 10
In [2]: print a
10

ipython shell,

In [3]: 5000 / 1.05


Out[3]: 4761.9047619047615
In [4]: Out[3]
Out[4]: 4761.9047619047615

Out list, 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

system specific randomness source if available.


If a is not None or an int or long, hash(a) is used instead.
"""
if a is None:
try:
a = long(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
a = long(time.time() * 256) # use fractional seconds
super(Random, self).seed(a)
self.gauss_next = None

! 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

In [24]: doamin_name = 'www.google.com.tw'


In [25]: !nslookup $doamin_name
Server: 168.95.1.1
Address: 168.95.1.1#53
Non-authoritative answer:
Name: www.google.com.tw
Address: 74.125.203.94

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'

Tk Geometry in command line


Grid
Layout.

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):

button = Tkinter.Button(root, text="B")


command = ButtonCommand(row, col)
button['command'] = command.on_click
button.grid(row=row, column=col)
root.mainloop()

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))

for row in range(10):


for col in range(10):
button = CB(root, row=row, col=col, text="B")
button.grid(row=row, column=col)
root.mainloop()

! !
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

a[ (0, 2) ] = 'no bomb'


a[ (0, 1) ] = 'bomb'
print(a) # {(0, 1): 'bomb', (0, 2): 'no bomb'}

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,

(2, 0): 0, (2, 1): 0, (2, 2): 0,


}
TOTAL_SPACES = len(LAYOUT) - sum(LAYOUT.values())
GAME_NUMBERS = {
(0, 0): 1, (0, 1): 1, (0, 2): 0,
(1, 0): 0, (1, 1): 1, (1, 2): 0,
(2, 0): 1, (2, 1): 1, (2, 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

usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]


or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help

timdeMacBook-Pro:PySetupExample tim$ python setup.py --help-commands


Standard commands:
build build everything needed to install
build_py "build" pure Python modules (copy to build directory)
build_ext build C/C++ extensions (compile/link to build directory)
build_clib build C/C++ libraries used by Python extensions
build_scripts "build" scripts (copy and fixup #! line)

clean clean up temporary files from 'build' command


install install everything from build directory
install_lib install all Python modules (extensions and pure Python)
install_headers install C/C++ header files
install_scripts install scripts (Python or otherwise)
install_data install data files
sdist create a source distribution (tarball, zip file, etc.)
register register the distribution with the Python package index
bdist create a built (binary) distribution
bdist_dumb create a "dumb" built distribution
bdist_rpm create an RPM distribution
bdist_wininst create an executable installer for MS Windows
upload upload binary package to PyPI
check perform some checks on the package

sudo python setup.py install

pip freeze | grep SetupSample

... ...

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'], ##
)

sudo python setup.py install

python shell import 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', ],
)

sudo python setup.py install

cat2

cat2

pip uninstall SetupSample

pip freeze | grep Sam #

githib butbucket

github Repository,

sudo rm -rf build


sudo rm -rf *.pyc
git init
git add *
git commit -m init
git remote add origin https://github.com/timtan/setup-py-example.git # Repo
git push -u origin master

sudo pip install git+https://github.com/timtan/setup-py-example


URL git+

github
PyPi Repository, github

You might also like