鍍金池/ 教程/ Python/ 對象與參考
備份腳本——版本四
使用 <strong>init</strong> 方法
控制流
異常
表 15.1 一些特殊的方法
如何創(chuàng)建你自己的模塊
使用字典
前言
使用默認參數(shù)值
表 5.1 運算符與它們的用法
解決問題——編寫一個 Python 腳本
使用 for 語句
使用 continue 語句
使用元組輸出
對象與參考
使用函數(shù)形參
使用默認參數(shù)值
使用 if 語句
如何引發(fā)異常
使用源文件
使用對象的方法
使用表達式
定義函數(shù)
使用局部變量
使用列表綜合
使用 sys.argv
使用 lambda 形式
使用 global 語句
備份腳本——版本二
使用列表
使用 while 語句
備份腳本——版本一
使用元組
輸入/輸出
使用類與對象的變量
使用 sys 模塊
表 5.2 運算符優(yōu)先級
處理異常
使用 break 語句
函數(shù)
基本概念
運算符與表達式
介紹
使用文件
使用序列
接下來學習什么?
使用帶提示符的 Python 解釋器
使用 DocStrings
使用字面意義上的語句
最初的步驟
數(shù)據(jù)結構
儲存與取儲存
使用 dir 函數(shù)
模塊
Python 標準庫
備份腳本——版本三(不工作?。?/span>
創(chuàng)建一個類
安裝 Python
面向對象的編程
使用模塊的<strong>name</strong>
使用變量和字面意義上的常量
使用繼承

對象與參考


    #!/usr/bin/python
    # Filename: reference.py

    print 'Simple Assignment'
    shoplist = ['apple', 'mango', 'carrot', 'banana']
    mylist = shoplist # mylist is just another name pointing to the same object!

    del shoplist[0]

    print 'shoplist is', shoplist
    print 'mylist is', mylist
    # notice that both shoplist and mylist both print the same list without
    # the 'apple' confirming that they point to the same object

    print 'Copy by making a full slice'
    mylist = shoplist[:] # make a copy by doing a full slice
    del mylist[0] # remove first item

    print 'shoplist is', shoplist
    print 'mylist is', mylist
    # notice that now the two lists are different

(源文件:code/reference.py

輸出


    $ python reference.py
    Simple Assignment
    shoplist is ['mango', 'carrot', 'banana']
    mylist is ['mango', 'carrot', 'banana']
    Copy by making a full slice
    shoplist is ['mango', 'carrot', 'banana']
    mylist is ['carrot', 'banana']

它如何工作

大多數(shù)解釋已經在程序的注釋中了。你需要記住的只是如果你想要復制一個列表或者類似的序列或者其他復雜的對象(不是如整數(shù)那樣的簡單 對象 ),那么你必須使用切片操作符來取得拷貝。如果你只是想要使用另一個變量名,兩個名稱都 參考 同一個對象,那么如果你不小心的話,可能會引來各種麻煩。

給 Perl 程序員的注釋
記住列表的賦值語句創(chuàng)建拷貝。你得使用切片操作符來建立序列的拷貝。

上一篇:面向對象的編程下一篇:使用繼承