Ò׽ؽØÍ¼Èí¼þ¡¢µ¥Îļþ¡¢Ãâ°²×°¡¢´¿ÂÌÉ«¡¢½ö160KB

PythonÄ£¿éѧϰ

¡¡¡¡copyÄ£¿éÓÃÓÚ¶ÔÏóµÄ¿½±´²Ù×÷¡£¸ÃÄ£¿é·Ç³£¼òµ¥£¬Ö»ÌṩÁËÁ½¸öÖ÷ÒªµÄ·½·¨£º
copy.copy
Óë
copy.deepcopy
£¬·Ö±ð±íʾdz¸´ÖÆÓëÉî¸´ÖÆ¡£Ê²Ã´ÊÇdz¸´ÖÆ£¬Ê²Ã´ÊÇÉî¸´ÖÆ£¬ÍøÉÏÓÐÒ»¿¨³µÒ»¿¨³µµÄ×ÊÁÏ£¬ÕâÀï²»×÷Ïêϸ½éÉÜ¡£¸´ÖƲÙ×÷Ö»¶Ô¸´ºÏ¶ÔÏóÓÐЧ¡£Óüòµ¥µÄÀý×ÓÀ´·Ö±ð½éÉÜÕâÁ½¸ö·½·¨¡£
dz¸´ÖÆÖ»¸´ÖƶÔÏó±¾Éí£¬Ã»Óи´ÖƸöÔÏóËùÒýÓõĶÔÏó¡£
#coding=gbk
import copy
l1 = [1, 2, [3, 4]]
l2 = copy.copy(l1)
print l1
print l2
l2[2][0] = 50
print l1
print l2
#---- ½á¹û ----
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]
[1, 2, [50, 4]]
ͬÑùµÄ´úÂ룬ʹÓÃÉî¸´ÖÆ£¬½á¹û¾Í²»Ò»Ñù£º
import copy
l1 = [1, 2, [3, 4]]
l2 = copy.deepcopy(l1)
print l1
print l2
l2[2][0] = 50
print l1
print l2
#---- ½á¹û ----
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [3, 4]]
[1, 2, [50, 4]]

¸Ä±äcopyµÄĬÈÏÐÐΪ
¡¡¡¡ÔÚ¶¨ÒåÀàµÄʱºò£¬Í¨¹ý¶¨Òå__copy__ºÍ__deepcopy__·½·¨£¬¿ÉÒԸıäcopyµÄĬÈÏÐÐΪ¡£ÏÂÃæÊÇÒ»¸ö¼òµ¥µÄÀý×Ó:
class CopyObj(object):
def __repr__(self):
return "CopyObj"

def __copy__(self):
return "Hello"
obj = CopyObj()
obj1 = copy.copy(obj)
print obj
print obj1
#---- ½á¹û ----
CopyObj
Hello


Ïà¹ØÎĵµ£º

PythonÄ£¿éѧϰ

¡¡¡¡ÓÐʱºò£¬Òª°ÑÄÚ´æÖеÄÒ»¸ö¶ÔÏó³Ö¾Ã»¯±£´æµ½´ÅÅÌÉÏ£¬»òÕßÐòÁл¯³É¶þ½øÖÆÁ÷ͨ¹ýÍøÂç·¢Ë͵½Ô¶³ÌÖ÷»úÉÏ¡£PythonÖÐÓкܶàÄ£¿éÌṩÁËÐòÁл¯Óë·´ÐòÁл¯µÄ¹¦ÄÜ£¬È磺marshal, pickle, cPickleµÈµÈ¡£½ñÌì¾Í½²½²marshalÄ£¿é¡£
¡¡¡¡×¢Ò⣺
marshal²¢²»ÊÇÒ»¸öͨÓõÄÄ£¿é£¬ÔÚijЩʱºòËüÊÇÒ»¸ö²»±»ÍƼöʹÓõÄÄ£¿é£¬ÒòΪʹÓÃmarshalÐ ......

PythonÈëÃŵÄ36¸öÀý×Ó Ö® 23

Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
# 026
aList = ['1','2','3','4']
aListCopy = aList # Æäʵ£¬ÕâÀï½ö½ö¸´ÖÆÁËÒ»¸öÒýÓÃ
del aList[0]
print aList
print aListCopy # Á½¸öÒýÓÃÖ¸ÏòÁËÁËͬһ¸ö¶ÔÏó£¬ËùÒÔ´òÓ¡½á¹ûÒ»Ñù
aListCopy = aList[:] # ÕâÊǸ´ÖÆÕû¸ö¶ÔÏóµÄÓÐЧ·½·¨
del aList[0]
print aList
print aListCopy
......

PythonÈëÃŵÄ36¸öÀý×Ó Ö® 26

Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
# 029
aFile = file(r'C:\in.txt', 'r')
while True:
line = aFile.readline()
if len(line) == 0:
break
# end of if
print line,
# end of while
aFile.close()

output£º
>>>
This is the first line.
This is the second line.
This is ......

PythonÈëÃŵÄ36¸öÀý×Ó Ö® 34

Ô´´úÂëÏÂÔØ£ºÏÂÔØµØÖ·ÔÚÕâÀï
raiseÓÐÁ½¸ö²ÎÊý£¬µÚÒ»¸öÊÇÓÉÎÒÃÇ×Ô¼º¶¨ÒåµÄÒì³£ÀàÐÍ£¬µÚ¶þ¸öÊǹØÓÚ´ËÒì³£µÄÉÙÁ¿ËµÃ÷ÐÅÏ¢¡£
# 038
def getAge():
age = input('Input your age:')
if (age < 0 or age > 160):
raise 'BadAgeError', 'It is impossible!!!!!'
# end of if
return age
# ......

PythonÈëÃŵÄ36¸öÀý×Ó Ö® 36

# 040
import time
try:
f = file('040_Finally.py')
while True:
line = f.readline()
if len(line) == 0:
break
time.sleep(0.33)
print line,
# end of while
finally:
f.close()
print 'Closed the file.'
# end of try
output£º
> ......
© 2009 ej38.com All Rights Reserved. ¹ØÓÚE½¡ÍøÁªÏµÎÒÃÇ | Õ¾µãµØÍ¼ | ¸ÓICP±¸09004571ºÅ