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ÖÐÓкܶàÄ£¿éÌṩÁËÐòÁл¯Óë·´ÐòÁл¯µÄ¹¦ÄÜ£¬È磺marshal, pickle, cPickleµÈµÈ¡£½ñÌì¾Í½²½²marshalÄ£¿é¡£
¡¡¡¡×¢Ò⣺
marshal²¢²»ÊÇÒ»¸öͨÓõÄÄ£¿é£¬ÔÚijЩʱºòËüÊÇÒ»¸ö²»±»ÍƼöʹÓõÄÄ£¿é£¬ÒòΪʹÓÃmarshalÐ ......
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
# 022
listNum1 = [1, 3]
listNum2 = [2, 4]
listStr1 = ['a', 'c']
listStr2 = ['b', 'd']
# ÁбíµÄºÏ²¢
list1 = listNum1 + listStr1
for ele in list1:
print ele
print '\n'
# ÅжÏÁбíÖÐÊÇ·ñ°üº¬Ä³ÔªËØ
print 'b' in list1
print 1 in list1
# ɾ³ýij¸öÔªËØ
for ele in ......
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
# 034
class Person:
def __init__(self, name):
self.name = name # ÕâÒ»¾äÖеÚÒ»¸önameÊÇÀàÖаüº¬µÄÓò£¬µÚ¶þ¸önameÊÇ´«½øÀ´µÄ²ÎÊý
# end of def
def sayHello(self):
print 'Hello!'
# end of def
# end of class
p = Person('Ning')
print p.nam ......
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
# 035
class Person:
population = 0 #Õâ¸ö±äÁ¿ÊÇÊôÓÚÕû¸öÀàµÄ
def __init__(self, name):
self.name = name
print '³õʼ»¯ %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self. ......