1. 程式人生 > >我要學python之函數與模塊

我要學python之函數與模塊

utc 整數 minute sam platform 也會 技術 棧內存 lib

函數

這概念和c語言中的函數呀,java中的方法概念其實是一樣的。
函數是組織好的,可重復使用的,用來實現單一,或相關聯功能的代碼段。

比如說,java中的System.out.println(....)也就是一個方法,python中的print(.....),這些是各個語言的內置函數,我們也可以自定義函數,被叫做:用戶自定義函數

函數定義

1.函數代碼塊以 def 關鍵詞開頭,後接函數標識符名稱和圓括號()。
2.任何傳入參數和自變量必須放在圓括號中間。圓括號之間可以用於定義參數。
3.函數的第一行語句可以選擇性地使用文檔字符串—用於存放函數說明。
4.函數內容以冒號起始,並且縮進。
5.return [表達式] 結束函數,選擇性地返回一個值給調用方。不帶表達式的return相當於返回 None。

比如說我們現在需要定義一個函數,該函數功能是把傳入的元組進行進行排序

#定義函數
def println(paramters):
    "函數說明:打印傳入的字符串到標準顯示設備上,每次輸出空一行"
    print(paramters + "\n")
    return

#函數調用
println("My name is ckmike...")
println("hello!")
println("what‘s the fuck!")

函數參數傳遞

我們在前一篇中寫的猜數字遊戲小程序中代碼為例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#預設猜數值
realnumber = 35
#猜測數字次數
times = 3

#循環進行程序輸入判斷
while times > 0:
    target = int(input("請輸入數字:"))
    #判斷是否與目標數值相等
    if target == realnumber:
        print("bingo!")
        break
    elif target > realnumber:
        print("輸入的值比目標值大!")
    else:
        print("輸入數值比目標數值小!")
    times -= 1
else:
    print("三次機會已經用完!")

從上面的代碼,我們知道realnumber變量、times變量,我們知道不管java還是c#,都是在變量前必須限定這個變量類型,因為他們都是強類型語言( 目前是這樣,後面發展也許會有改變也不一定。)。而python中的變量是沒有類型的,python是弱類型語言。
我們再看下面代碼:

a = [12,13,14]
a = "CkMike"

前一行a指向了一個list的列表,後一句則指向了一個字符串。
在 python 中,strings, tuples, 和 numbers 是不可更改的對象,而 list,dict 等則是可以修改的對象。
不可變類型:變量賦值 a=5 後再賦值 a=10,這裏實際是新生成一個 int 值對象 10,再讓 a 指向它,而 5 被丟棄,不是改變a的值,相當於新生成了a。

可變類型:變量賦值 a=[1,2,3,4] 後再賦值 a[2]=5 則是將 list la 的第三個元素值更改,本身a沒有動,只是其內部的一部分值被修改了。

python 函數的參數傳遞

不可變類型:類似 c++ 的值傳遞,如 整數、字符串、元組。如fun(a),傳遞的只是a的值,沒有影響a對象本身。比如在 fun(a)內部修改 a 的值,只是修改另一個復制的對象,不會影響 a 本身。

可變類型:類似 c++ 的引用傳遞,如 列表,字典。如 fun(la),則是將 la 真正的傳過去,修改後fun外部的la也會受影響

不可變類型參數演示

def plus(num):
    num = 100

a = 30
plus(a)
print(a)

結果輸出還是30

可變類型參數演示

# 可寫函數說明
def changelist( mylist ):
   "修改傳入的列表"
   mylist.append(1);
   mylist.append(2);
   mylist.append(3);
   print("函數內取值:", mylist)
   return

target = [‘a‘,‘b‘,‘c‘,‘d‘]
changelist(target)
print(target)

技術分享圖片

#可寫函數說明
def printinfo( name, *boxes, age = 21, sex = ‘男‘ ):
   "打印任何傳入的字符串"
   print("Name: ", name)
   print("Age ", age)
   print("Sex ", sex)
   print("購買了如下包:")
   #遍歷輸出boxes的名字
   for box in boxes:
       print(box)
   return

#調用
printinfo("ckgirl","LV","Prada","KUQI", age= 25, sex="女")

總結:
1.參數可以給定默認值,給定默認值,則該參數為選填
2.選填參數必須放置在最後面
3.不定長參數必須放置定長必填參數後面且放置在選填參數前面
4.傳遞參數時,可以使用形參關鍵字傳遞指定的參數,可以不關心先後順序,但要註意不定長參數位置一定要準守3規則,不管是定義還是調用傳遞參數時。

匿名函數

python 使用 lambda 來創建匿名函數。
lambda只是一個表達式,函數體比def簡單很多。
lambda的主體是一個表達式,而不是一個代碼塊。僅僅能在lambda表達式中封裝有限的邏輯進去。
lambda函數擁有自己的命名空間,且不能訪問自有參數列表之外或全局命名空間裏的參數。
雖然lambda函數看起來只能寫一行,卻不等同於C或C++的內聯函數,後者的目的是調用小函數時不占用棧內存從而增加運行效率。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# 可寫函數說明
sum = lambda arg1, arg2: arg1 + arg2;

# 調用sum函數
print("相加後的值為 : ", sum( 10, 20 ))
print("相加後的值為 : ", sum( 20, 20 ))

變量作用域

全局變量、局部變量
定義在函數內部的變量擁有一個局部作用域,定義在函數外的擁有全局作用域。
局部變量只能在其被聲明的函數內部訪問,而全局變量可以在整個程序範圍內訪問。調用函數時,所有在函數內聲明的變量名稱都將被加入到作用域中。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

total = 0;  # 這是一個全局變量

# 可寫函數說明
def sum(arg1, arg2):
    # 返回2個參數的和."
    total = arg1 + arg2;  # total在這裏是局部變量.
    print("函數內是局部變量 : ", total)
    return total;

# 調用sum函數
sum(10, 20);
print("函數外是全局變量 : ", total)

模塊

Python 模塊(Module),是一個 Python 文件,以 .py 結尾,包含了 Python 對象定義和Python語句。模塊讓你能夠有邏輯地組織你的 Python 代碼段。把相關的代碼分配到一個模塊裏能讓你的代碼更好用,更易懂。模塊能定義函數,類和變量,模塊裏也能包含可執行的代碼。

# 引入time模塊
import time

# 調用模塊中函數,獲取當前時間戳
print(time.time())

我們可以自行去查看time.py這個模塊代碼,如下:

# encoding: utf-8
# module time
# from (built-in)
# by generator 1.145
"""
This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer
or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
The actual value can be retrieved by calling gmtime(0).

The other representation is a tuple of 9 integers giving local time.
The tuple items are:
  year (including century, e.g. 1998)
  month (1-12)
  day (1-31)
  hours (0-23)
  minutes (0-59)
  seconds (0-59)
  weekday (0-6, Monday is 0)
  Julian day (day in the year, 1-366)
  DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.

Variables:

timezone -- difference in seconds between UTC and local standard time
altzone -- difference in  seconds between UTC and local DST time
daylight -- whether local time should reflect DST
tzname -- tuple of (standard time zone name, DST time zone name)

Functions:

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
"""
# no imports

# Variables with simple values

altzone = -32400

daylight = 0

timezone = -28800

_STRUCT_TM_ITEMS = 11

# functions

def asctime(p_tuple=None): # real signature unknown; restored from __doc__
    """
    asctime([tuple]) -> string

    Convert a time tuple to a string, e.g. ‘Sat Jun 06 16:26:11 1998‘.
    When the time tuple is not present, current time as returned by localtime()
    is used.
    """
    return ""

def clock(): # real signature unknown; restored from __doc__
    """
    clock() -> floating point number

    Return the CPU time or real time since the start of the process or since
    the first call to clock().  This has as much precision as the system
    records.
    """
    return 0.0

def ctime(seconds=None): # known case of time.ctime
    """
    ctime(seconds) -> string

    Convert a time in seconds since the Epoch to a string in local time.
    This is equivalent to asctime(localtime(seconds)). When the time tuple is
    not present, current time as returned by localtime() is used.
    """
    return ""

def get_clock_info(name): # real signature unknown; restored from __doc__
    """
    get_clock_info(name: str) -> dict

    Get information of the specified clock.
    """
    return {}

def gmtime(seconds=None): # real signature unknown; restored from __doc__
    """
    gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
                           tm_sec, tm_wday, tm_yday, tm_isdst)

    Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
    GMT).  When ‘seconds‘ is not passed in, convert the current time instead.

    If the platform supports the tm_gmtoff and tm_zone, they are available as
    attributes only.
    """
    pass

def localtime(seconds=None): # real signature unknown; restored from __doc__
    """
    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                              tm_sec,tm_wday,tm_yday,tm_isdst)

    Convert seconds since the Epoch to a time tuple expressing local time.
    When ‘seconds‘ is not passed in, convert the current time instead.
    """
    pass

def mktime(p_tuple): # real signature unknown; restored from __doc__
    """
    mktime(tuple) -> floating point number

    Convert a time tuple in local time to seconds since the Epoch.
    Note that mktime(gmtime(0)) will not generally return zero for most
    time zones; instead the returned value will either be equal to that
    of the timezone or altzone attributes on the time module.
    """
    return 0.0

def monotonic(): # real signature unknown; restored from __doc__
    """
    monotonic() -> float

    Monotonic clock, cannot go backward.
    """
    return 0.0

def perf_counter(): # real signature unknown; restored from __doc__
    """
    perf_counter() -> float

    Performance counter for benchmarking.
    """
    return 0.0

def process_time(): # real signature unknown; restored from __doc__
    """
    process_time() -> float

    Process time for profiling: sum of the kernel and user-space CPU time.
    """
    return 0.0

def sleep(seconds): # real signature unknown; restored from __doc__
    """
    sleep(seconds)

    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.
    """
    pass

def strftime(format, p_tuple=None): # real signature unknown; restored from __doc__
    """
    strftime(format[, tuple]) -> string

    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used.

    Commonly used format codes:

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale‘s abbreviated weekday name.
    %A  Locale‘s full weekday name.
    %b  Locale‘s abbreviated month name.
    %B  Locale‘s full month name.
    %c  Locale‘s appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale‘s equivalent of either AM or PM.

    Other codes may be available on your platform.  See documentation for
    the C library strftime function.
    """
    return ""

def strptime(string, format): # real signature unknown; restored from __doc__
    """
    strptime(string, format) -> struct_time

    Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as
    strftime()).

    Commonly used format codes:

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale‘s abbreviated weekday name.
    %A  Locale‘s full weekday name.
    %b  Locale‘s abbreviated month name.
    %B  Locale‘s full month name.
    %c  Locale‘s appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale‘s equivalent of either AM or PM.

    Other codes may be available on your platform.  See documentation for
    the C library strftime function.
    """
    return struct_time

def time(): # real signature unknown; restored from __doc__
    """
    time() -> floating point number

    Return the current time in seconds since the Epoch.
    Fractions of a second may be present if the system clock provides them.
    """
    return 0.0

# classes

class struct_time(tuple):
    """
    The time value as returned by gmtime(), localtime(), and strptime(), and
     accepted by asctime(), mktime() and strftime().  May be considered as a
     sequence of 9 integers.

     Note that several fields‘ values are not the same as those defined by
     the C language standard for struct tm.  For example, the value of the
     field tm_year is the actual year, not year - 1900.  See individual
     fields‘ descriptions for details.
    """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    tm_gmtoff = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """offset from UTC in seconds"""

    tm_hour = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """hours, range [0, 23]"""

    tm_isdst = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """1 if summer time is in effect, 0 if not, and -1 if unknown"""

    tm_mday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of month, range [1, 31]"""

    tm_min = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """minutes, range [0, 59]"""

    tm_mon = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """month of year, range [1, 12]"""

    tm_sec = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """seconds, range [0, 61])"""

    tm_wday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of week, range [0, 6], Monday is 0"""

    tm_yday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of year, range [1, 366]"""

    tm_year = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """year, for example, 1993"""

    tm_zone = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """abbreviation of timezone name"""

    n_fields = 11
    n_sequence_fields = 9
    n_unnamed_fields = 0

class __loader__(object):
    """
    Meta path import for built-in modules.

        All methods are either class or static methods to avoid the need to
        instantiate the class.
    """
    @classmethod
    def create_module(cls, *args, **kwargs): # real signature unknown
        """ Create a built-in module """
        pass

    @classmethod
    def exec_module(cls, *args, **kwargs): # real signature unknown
        """ Exec a built-in module """
        pass

    @classmethod
    def find_module(cls, *args, **kwargs): # real signature unknown
        """
        Find the built-in module.

                If ‘path‘ is ever specified then the search is considered a failure.

                This method is deprecated.  Use find_spec() instead.
        """
        pass

    @classmethod
    def find_spec(cls, *args, **kwargs): # real signature unknown
        pass

    @classmethod
    def get_code(cls, *args, **kwargs): # real signature unknown
        """ Return None as built-in modules do not have code objects. """
        pass

    @classmethod
    def get_source(cls, *args, **kwargs): # real signature unknown
        """ Return None as built-in modules do not have source code. """
        pass

    @classmethod
    def is_package(cls, *args, **kwargs): # real signature unknown
        """ Return False as built-in modules are never packages. """
        pass

    @classmethod
    def load_module(cls, *args, **kwargs): # real signature unknown
        """
        Load the specified module into sys.modules and return it.

            This method is deprecated.  Use loader.exec_module instead.
        """
        pass

    def module_repr(module): # reliably restored by inspect
        """
        Return repr for the module.

                The method is deprecated.  The import machinery does the job itself.
        """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """list of weak references to the object (if defined)"""

    __dict__ = None # (!) real value is ‘‘

# variables with complex values

tzname = (
    ‘?D1ú±ê×?ê±??‘,
    ‘?D1ú??á?걑,
)

__spec__ = None # (!) real value is ‘‘

總結:
上面用import 後面接模塊名的方式導入整個模塊,模塊會導入一次,且只會導入一次,不管你import了幾次該模塊。

但有時候我只想引入模塊中的某一個函數式該如何導入呢?

from 模塊名 import 目標對象

備註:
from 模塊名 import * 等效於import 模塊名

這個其實很簡單,就跟前端中的import模塊是一樣的,相比較與java和C#類似於從一個命名空間中引入下列的對應類,比如說:

// 導入指定的對象
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
// 這就把util包下的所有對象都導入了
import java.util.*;

python中的包

包是一個分層次的文件目錄結構,它定義了一個由模塊及子包,和子包下的子包等組成的 Python 的應用環境。
簡單來說,包就是文件夾,但該文件夾下必須存在 init.py 文件, 該文件的內容可以為空。init.py 用於標識當前文件夾是一個包。
這個你可以用pycharm開發工具創建一個試一下。
可以根據自己定義內容。
init.py文件內容如下:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

if __name__ == ‘__main__‘:
    print(‘作為主程序運行‘)
else:
    print(‘初始化‘)

我要學python之函數與模塊