01. python 入門

最後更新: 2018-10-12

目錄

  • 查看系統上 python 的 version
  • 進入 Shell 與 comment "#"
  • Shell 內 hotkey
  • Script File
  • Function
  • *t 與 **d
  • Modules
  • Class
  • Input 與 raw_input
  • exec 與 eval
  • Code 內有中文
  • assert
  • enumerate
  • yield
  • underscore "_"
  • _X __X __X__
  • __future__
  • Assert
  • Type casting(Conversion)
  • Troubleshoot

 


查看系統上 python 的 version

 

python -V            #  須要查看的原因是因為 python 2.x 與 3.x 是很大不同的 !! 一個 program 在 2.6 行到, 在 3.X 已經行唔到了

Python 2.6.6

 


進入 Shell 與 comment "#"

 

python              # 進入 Shell

>>># This is a comment

Ctrl + D            # 離開 Shell

 


Shell 內 hotkey

 

Ctrl + d 離開 PY Shell

Ctrl + c 中斷執行中的指令

 


Script File

 

Script 一般以 "#!/usr/bin/env python" 開頭

#!/usr/bin/env python
# coding=utf-8
# vim: sts=4:ts=4:sw=4:paste
# Filename : helloworld.py

print 'Hello World'

 


Check Var is Null

 

1. Variable define

try:
    myVar
except NameError:
    print "No myVar"
    sys.exit()

2. globals 與 locals

if 'myVar' in globals():
  # myVar exists.

if 'myVar' in locals():
  # myVar exists.

3. check None

# NameError: name 'msg' is not defined
if foo is None:
    ...

 


Global Variable

 

Each file has its own global variable

The function always remembers where it was created

Python is “pass by reference”

Using a separate file to hold GLOBAL variable across multiple Python files

i.e. MyGlobal.py

from web.contrib.template import render_jinja

# jinja
render = render_jinja(
        'templates',
        encoding = 'utf-8',
    )

index.py

from MyGlobal import render

 


Function

 

 * in Python, functions are objects

example1:

def add(a,b):
    return a+b

print add(1,2)

example2:

a_string = "This is a global variable"
def foo():
    print locals()               # 沒有 var, 所以 result 是 '{}'
    print a_string               # 可以支接拎 Global variable

print globals()
# {..., 'a_string': 'This is a global variable', 'foo': <function foo at 0x0000000002609518>}

P.S.

python函數傳遞參數的方式有兩種, 分別是

*args <= ()

**kwargs <= {}

DOC

Built-in Functions: https://docs.python.org/2/library/functions.html

 


*t 與 **d

 

*args = Non Keyword Arguments

**kwargs = Keyword Arguments

*t 與 **d 有機會出現的地方

  • In a function call
  • In a function signature
  • In assignments

In a function call

# *t   treat the elements of this iterable as positional arguments

foo(*t)

應用

def foo(a, b, c):
    print a
    print b
    print c
    
t=(1,2,3)
#foo(*t)
foo(t)

# **d  treat the key-value pairs in the dictionary as additional named arguments

foo(**d)

In a function signature

使用情況: Unsure about the number of arguments to pass in the functions.

pack them into this parameter as a tuple t (亦即係 group 成一個 tuple)

def foo(*t):
    print(t)

insert them into d as dictionary entries.

def foo(**d):
    print(d)

In assignment

x, *y, z = (1, 2, 3, 4)

 


Modules

 

import Syntax

from package_name import ClassName

ie.

from filename import class
from common import loadconfig, mail2admin
from filename import *
from math import sqrt as sq

查看 Model 的說明

>>> import web
>>> dir(web)
['Accepted', 'AppBrowser', ...]

SubFolder as Package

SubFolder 內儲放 __init__.py 檔案時,

Python 就會將這個目錄視為一個 Package, 而目錄名稱就是 Package 名稱

SubFolder 內的 filename.py 的 filename 就是 module_name

i.e.

import SubFolder
import SubFolder.filename

__init__.py

- used to mark directories on disk as Python package directories

- execute initialization code for the package

- set the __all__ variable

├── libs
│   ├── file1.py
│   ├── file2.py
│   ├── file3.py
│   └── __init__.py
└── test.py

1) 用 __init__.py 設定 "as"

原本寫法

test.py

from libs.file1 import mytest as mytest1
from libs.file2 import mytest as mytest2

i.e.

當 __inti__.py 設定好 import 咩 package 時

__init__.py

from file1 import mytest as mytest1
from file2 import mytest as mytest2

那 test.py 就可以寫成

from libs import mytest1
from libs import mytest2

2) 限制 "*" import 什麼

__init__.py

__all__ = ['mytest1', 'mytest2']

test.py

from subpackage import *
print mytest1 + mytest3

# 會有 Error: "NameError: name 'mytest3' is not defined"

# 將 "2" 改成 "3" 就無事了

 


Class

 

Defining a class

class My2D:
    """ doc about your class"""
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __str__(self):
        return ""
    __private_var = 0

__doc__

相當於第一行的 """" ... """"

__init__(self, v1, v2 ...)

constructor

__str__

built-in method, print an instance

__class__.__name__

class 的名稱

class A:
    def __init__(self):
        print self.__class__.__name__

a = A()      # A

應用

if __name__ == '__main__':
    print "test"

private varable

start with 2 underscores

Create Object

my2d = My2D(1,2)
print my2d.x, my2d.y

Inheritance

class My3D(My2D):
    # Override Constructor
    def __init__(self,x):
        self.x = x
        self.y = y
        self.z = z

Calling Parent Class constructor

Code:

class My3D(My2D):
    def __init__(self,x,y,z):
        My2D.__init__(self,x,y)
        self.z = z

Test:

my3d = My3D(1,2,3)
print my3d.x, my3d.y, my3d.z

 


Input 與 raw_input

 

mystr = input("Pls input a string: ")    # 當 input 的是數字來是沒有問題的, 不過 string 沒有 "" 時, 那就會報錯

print mystr                                        # input 收的要是 python 表達的 input
                                                        # 所以, 一般而言, 用 raw_input("") 會較好
 

x, y, z = 1, 2, 3

x, y = y, x

 

 


exec 與 eval

 

  • 'string' code on the fly
  • exec executes a series of Python statements (沒有 return)
  • eval evaluates a Python expression (有 return)

scope = {}
x=1
exec 'x = 2' in scope              # print x 時會見到 1, print len(scope) 會見到 2
eval('x*x', scope)                  # eval 在另一個 scope 的表達方法

 

 


Code 內有中文

 

所有 Source 檔 default 都是用 ASCII 來 encode 的,
亦即是說中文的 comment 都會誤以為 ASCII,
所以當執行時會報錯,
解決方法是在檔頭要加上

#!/usr/bin/env python
# coding=utf-8

 


assert

 

# 斷定該時間點上,某變數必然是某值
# test 是狀態測試, test 結果為 True 或 False
# 而 message是斷言失敗時所要呈現訊息.
# 當 test 失敗後, 會有 AssertionError exception

assert <test>, <message>

i.e.

assert amount > 0, '必須是大於 0 的正數'

 


range

 

# 但不包括 stop

range(start, stop[, step])

Example

>>> for n in range(1,5):
...     print n
...
1
2
3
4

 


enumerate

 

i.e.

import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)

output:

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21, 'v'), (22, 'w'), (23, 'x'), (24, 'y'), (25, 'z')]

i.e.

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

 


yield

 

yield就像是return會傳回值,但又不中斷函式的執行

>>> def myrange(n):
...     x = 0
...     while True:
...         yield x
...         x += 1
...         if x == n:
...             break
...

>>> for i in myrange(10):
...     print(i, end='')
... print()
...
0123456789

 

>>> g = myrange(3)
>>> next(g)
0
>>> next(g)
1
>>> next(g)
2

 


underscore "_"

 

"_"

for throwaway variables

In the interactive interpreter _ is used to reference the last returned value

Meanings

  1. For storing the value of last expression in interpreter.(used in interpreter)
  2. For ignoring the specific values(the values are not used)(so-called "I don't care")

[1]

>>> 3
3
>>> _
3
>>> _ * 3
9
>>> _
9

[2]

>>> for _ in range(5):
...     print "test"
...
test
test
test
test
test

 

 


"_X" "__X "__X__"

 

 

"_X"

Python doesn't have real private methods,

so one underline in the beginning of a method or attribute means you shouldn't access this method,

because it's not part of the API.

"__X"

This one causes a lot of confusion. It should not be used to mark a method as private, the goal here is to avoid your method to be overridden by a subclass

"__X__"

it's a method python calls, not you.

if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__".

If this file is being imported from another module, __name__ will be set to the module's name.

 


__future__

 

To get the 3.0 print function we do the following in Python 2.6:

from __future__ import print_function

* In Python 3, the keyword print has been changed from calling a statement to calling a function.
* SyntaxError: from __future__ imports must occur at the beginning of the file

Why not the following:

from __future__ import print

print_function is a FeatureName not be confused with the print built-in function itself.

DOC:

https://docs.python.org/2/library/__future__.html

 


Assert

 

所謂斷言(Assertion)指的是程式進行到某個時間點, 斷定其必然是某種狀態

# condition 是狀態測試, 而 message 是敗時所要呈現訊息

* immediately trigger an error if the condition is false.

assert condition [, "message"]

相當於

if not condition:
    raise AssertionError()

Try it

>>> assert True

>>> assert False

Remark

Do not use parenthesis"()" to call assert like a function. It is a statement.

 


Type casting(Conversion)

 

測試方式

  • type()
  • isinstance()

check type of variable

a = 1
print type(a)          # <type 'int'>
print type(str(a))     # <type 'str'>
print type(a)          # <type 'int'>

 


Troubleshoot

 

<1> ./?????.py:12: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6

Python: they got rid of the message member in favor of an args tuple.

def to_remote_error(error):
       ...
       message = error.message

to

def to_remote_error(error):
       ...
       message = error.args[0]

 


 

Creative Commons license icon Creative Commons license icon