锘??xml version="1.0" encoding="utf-8" standalone="yes"?>
]]>
#Filename:myAddressBook.py
import os
#used cPlickle store
import cPickle as p
########class Person##############
class Person:
def __init__(self,name,email):
self.name = name
self.email = email
def __del__(self):
pass
################################
#######class AddressBook#######
class AddressBook:
#the long name of data file
addressFile = 'Address.data'
#dictionary
addressList ={}
def __init__(self):
#If the data file of addressbook is not exists,then create it.
if not os.path.isfile(AddressBook.addressFile):
f = file(AddressBook.addressFile,'w')
p.dump(AddressBook.addressList,f)
f.close()
print 'Created file successfull!'
else:
#If the data file of addressbook is exists,then list all.
f = file(AddressBook.addressFile)
AddressBook.addressList = p.load(f)
print 'Current address list:'
f.close()
self.List()#call List function
#When destroy object,save data to file.
def __del__(self):
try:
try:
f = file(AddressBook.addressFile,'w')
p.dump(AddressBook.addressList,f)
print 'Save data successfull!'
except:
print 'Save data fail!'
finally:
f.close()
#purpose:Add new record
def Add(self,pepole):
if len(pepole.name)==0:
print 'The length of name must longer than zero.'
elif len(pepole.email)==0:
print 'The length of emial must longer than zero.'
else:
pr = Person(pepole.name,pepole.email)
AddressBook.addressList[pepole.name] = pr
print 'Add new person successfull!'
#purpose:Delete a record by name
def Del(self,name):
if AddressBook.addressList.has_key(name):
del AddressBook.addressList[name]
print 'Deleted %s successfull!' % name
else:
print 'The name is not exists.'
#purpose:Modify a record by name
def Edit(self,name,people):
if AddressBook.addressList.has_key(name):
AddressBook.addressList[name] = people
print 'Edit %s\'s information successfull!' % name
else:
print 'The name is not exists.'
#purpose:Find a record by name
def Find(self,name):
if AddressBook.addressList.has_key(name):
print '%s\'s information is :\nName:%s\nEmail:%s'\
% (name,\
AddressBook.addressList[name].name,\
AddressBook.addressList[name].email)
else:
print 'The name is not exists.'
#purpose:List all record
def List(self):
print '\n' + '*'*10 + 'Address List' + '*'*10 + '\n'
for name,people in AddressBook.addressList.items():
print '%s\'s information is :\nName:%s\nEmail:%s' % (name,people.name,people.email)
print '-'*30
################main####################################
os.system('clear')
ad = AddressBook()
while True:
print '\n' + '*'*10 + 'Main menu' + '*'*10 +'''
1.Add new address
2.Delete an address by name
3.Edit an address by name
4.Find an address by name
5.List all record
6.Exit'''+\
'\n' + '*'*30
try:
choice = int(raw_input('Please choice:'))
except:
os.system('clear')
print 'Error:Please enter a number from 1 to 6,enter again.'
continue
if choice == 1:
name = raw_input('Please input name:')
email = raw_input('Please input email:')
people = Person(name,email)
ad.Add(people)
elif choice == 2:
name = raw_input('Please input name:')
ad.Del(name)
elif choice == 3:
name = raw_input('Please input name:')
newemail = raw_input('Please input new email:')
people = Person(name,newemail)
ad.Edit(name,people)
elif choice == 4:
name = raw_input('Please input name:')
ad.Find(name)
elif choice == 5:
ad.List()
elif choice == 6:
break
else:
os.system('clear')
]]>
>>> i.append('item')
>>> `i`
"['item']"
>>> repr(i)
"['item']"
鍩烘湰涓婏紝repr鍑芥暟鍜屽弽寮曞彿鐢ㄦ潵鑾峰彇瀵硅薄鐨勫彲鎵撳嵃鐨勮〃紺哄艦寮忋備綘鍙互閫氳繃瀹氫箟綾葷殑__repr__
鏂規硶鏉ユ帶鍒朵綘鐨勫璞″湪琚玶epr鍑芥暟璋冪敤鐨勬椂鍊欒繑鍥炵殑鍐呭銆?
]]>
>>> assert len(mylist) >= 1
>>> mylist.pop()
'item'
>>> assert len(mylist) >= 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
]]>
鍚玃ython浠g爜鐨勫瓧絎︿覆錛岀劧鍚庝嬌鐢╡xec璇彞鎵ц榪欎簺璇彞銆備笅闈㈡槸涓涓畝鍗曠殑渚嬪瓙銆?br>>>> exec 'print "Hello World"'
Hello World
eval璇彞鐢ㄦ潵璁$畻瀛樺偍鍦ㄥ瓧絎︿覆涓殑鏈夋晥Python琛ㄨ揪寮忋?/strong>涓嬮潰鏄竴涓畝鍗曠殑渚嬪瓙銆?br>>>> eval('2*3')
]]>
#!/usr/bin/python
# Filename: lambda.py
def make_repeater(n):
return lambda s: s*n
twice = make_repeater(2)
print twice('word')
print twice(5)
$ python lambda.py
wordword
10
瀹冨浣曞伐浣?/strong>
榪欓噷錛屾垜浠嬌鐢ㄤ簡make_repeater鍑芥暟鍦ㄨ繍琛屾椂鍒涘緩鏂扮殑鍑芥暟瀵硅薄錛屽茍涓旇繑鍥炲畠銆俵ambda璇彞鐢?br>鏉ュ垱寤哄嚱鏁板璞°傛湰璐ㄤ笂錛宭ambda闇瑕佷竴涓弬鏁幫紝鍚庨潰浠呰窡鍗曚釜琛ㄨ揪寮忎綔涓哄嚱鏁頒綋錛岃岃〃杈懼紡
鐨勫艱榪欎釜鏂板緩鐨勫嚱鏁拌繑鍥炪?span style="COLOR: red">娉ㄦ剰錛屽嵆渚挎槸print璇彞涔熶笉鑳界敤鍦╨ambda褰㈠紡涓紝鍙兘浣跨敤琛ㄨ揪
寮忋?/span>
]]>
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
鐢變簬鍦╝rgs鍙橀噺鍓嶆湁*鍓嶇紑錛屾墍鏈夊浣欑殑鍑芥暟鍙傛暟閮戒細浣滀負涓涓厓緇勫瓨鍌ㄥ湪args涓傚鏋滀嬌鐢ㄧ殑
鏄?*鍓嶇紑錛屽浣欑殑鍙傛暟鍒欎細琚涓烘槸涓涓瓧鍏哥殑閿?鍊煎銆?/span>
]]>
#!/usr/bin/python
# Filename: list_comprehension.py
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo
杈撳嚭
$ python list_comprehension.py
[6, 8]
瀹冨浣曞伐浣?/strong>
榪欓噷鎴戜滑涓烘弧瓚蟲潯浠訛紙if i > 2錛夌殑鏁版寚瀹氫簡涓涓搷浣滐紙2*i錛夛紝浠庤屽鍑轟竴涓柊鐨勫垪琛ㄣ傛敞鎰忓師
鏉ョ殑鍒楄〃騫舵病鏈夊彂鐢熷彉鍖栥傚湪寰堝鏃跺欙紝鎴戜滑閮芥槸浣跨敤寰幆鏉ュ鐞嗗垪琛ㄤ腑鐨勬瘡涓涓厓绱狅紝鑰屼嬌
鐢ㄥ垪琛ㄧ患鍚堝彲浠ョ敤涓縐嶆洿鍔犵簿紜佺畝媧併佹竻妤氱殑鏂規硶瀹屾垚鐩稿悓鐨勫伐浣溿?
]]>
]]>
__init__(self,...) 榪欎釜鏂規硶鍦ㄦ柊寤哄璞℃伆濂借琚繑鍥炰嬌鐢ㄤ箣鍓嶈璋冪敤銆?br>__del__(self) 鎭板ソ鍦ㄥ璞¤琚垹闄や箣鍓嶈皟鐢ㄣ?br>__str__(self) 鍦ㄦ垜浠瀵硅薄浣跨敤print璇彞鎴栨槸浣跨敤str()鐨勬椂鍊欒皟鐢ㄣ?br>__lt__(self,other)褰撲嬌鐢?灝忎簬 榪愮畻絎︼紙<錛夌殑鏃跺欒皟鐢ㄣ傜被浼煎湴錛屽浜庢墍鏈夌殑榪愮畻絎?br>錛?錛?gt;絳夌瓑錛夐兘鏈夌壒孌婄殑鏂規硶銆?br>__getitem__(self,key)浣跨敤x[key]绱㈠紩鎿嶄綔絎︾殑鏃跺欒皟鐢ㄣ?br>__len__(self) 瀵瑰簭鍒楀璞′嬌鐢ㄥ唴寤虹殑len()鍑芥暟鐨勬椂鍊欒皟鐢ㄣ?
]]>
#!/usr/bin/python
# Filename: cat.py
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma
f.close()
# Script starts from here
if len(sys.argv) < 2:
print 'No action specified.'
sys.exit()
if sys.argv[1].startswith('--'):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help'''
else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
杈撳嚭
$ python cat.py
No action specified.
$ python cat.py --help
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help
$ python cat.py --version
Version 1.2
$ python cat.py --nonsense
Unknown option.
$ python cat.py poem.txt
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
]]>
Linux鍜學indows涓嬭繍琛屻備竴涓緥瀛愬氨鏄嬌鐢╫s.sep鍙互鍙栦唬鎿嶄綔緋葷粺鐗瑰畾鐨勮礬寰勫垎鍓茬銆?br>涓嬮潰鍒楀嚭浜嗕竴浜涘湪os妯″潡涓瘮杈冩湁鐢ㄧ殑閮ㄥ垎銆傚畠浠腑鐨勫ぇ澶氭暟閮界畝鍗曟槑浜嗐?br>鈼?nbsp; os.name瀛楃涓叉寚紺轟綘姝e湪浣跨敤鐨勫鉤鍙般傛瘮濡傚浜嶹indows錛屽畠鏄?nt'錛岃屽浜嶭inux/Unix
鐢ㄦ埛錛屽畠鏄?posix'銆?br>鈼?nbsp; os.getcwd()鍑芥暟寰楀埌褰撳墠宸ヤ綔鐩綍錛屽嵆褰撳墠Python鑴氭湰宸ヤ綔鐨勭洰褰曡礬寰勩?br>鈼?nbsp; os.getenv()鍜宱s.putenv()鍑芥暟鍒嗗埆鐢ㄦ潵璇誨彇鍜岃緗幆澧冨彉閲忋?br>鈼?nbsp; os.listdir()榪斿洖鎸囧畾鐩綍涓嬬殑鎵鏈夋枃浠跺拰鐩綍鍚嶃?br>鈼?nbsp; os.remove()鍑芥暟鐢ㄦ潵鍒犻櫎涓涓枃浠躲?br>鈼?nbsp; os.system()鍑芥暟鐢ㄦ潵榪愯shell鍛戒護銆?br>鈼?nbsp; os.linesep瀛楃涓茬粰鍑哄綋鍓嶅鉤鍙頒嬌鐢ㄧ殑琛岀粓姝㈢銆備緥濡傦紝Windows浣跨敤'\r\n'錛孡inux浣?br>鐢?\n'鑰孧ac浣跨敤'\r'銆?br>鈼?nbsp; os.path.split()鍑芥暟榪斿洖涓涓礬寰勭殑鐩綍鍚嶅拰鏂囦歡鍚嶃?br>>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
鈼?nbsp; os.path.isfile()鍜宱s.path.isdir()鍑芥暟鍒嗗埆媯楠岀粰鍑虹殑璺緞鏄竴涓枃浠惰繕鏄洰褰曘傜被浼煎湴錛宱s.
path.exists()鍑芥暟鐢ㄦ潵媯楠岀粰鍑虹殑璺緞鏄惁鐪熷湴瀛樺湪銆?
]]>
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up
closed the file'
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt
瀹冨浣曞伐浣?/strong>
鎴戜滑榪涜閫氬父鐨勮鏂囦歡宸ヤ綔錛屼絾鏄垜鏈夋剰鍦ㄦ瘡鎵撳嵃涓琛屼箣鍓嶇敤time.sleep鏂規硶鏆傚仠2縐掗挓銆傝繖鏍?br>鍋氱殑鍘熷洜鏄紼嬪簭榪愯寰楁參涓浜涳紙Python鐢變簬鍏舵湰璐ㄩ氬父榪愯寰楀緢蹇級銆傚湪紼嬪簭榪愯鐨勬椂鍊欙紝
鎸塁trl-c涓柇/鍙栨秷紼嬪簭銆?br>鎴戜滑鍙互瑙傚療鍒癒eyboardInterrupt寮傚父琚Е鍙戯紝紼嬪簭閫鍑恒備絾鏄湪紼嬪簭閫鍑轟箣鍓嶏紝finally浠庡彞浠?br>鐒惰鎵ц錛屾妸鏂囦歡鍏抽棴
]]>
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:
print 'No exception was raised.'
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
瀹冨浣曞伐浣?/strong>
榪欓噷錛屾垜浠垱寤轟簡鎴戜滑鑷繁鐨勫紓甯哥被鍨嬶紝鍏跺疄鎴戜滑鍙互浣跨敤浠諱綍棰勫畾涔夌殑寮傚父/閿欒銆傝繖涓柊
鐨勫紓甯哥被鍨嬫槸ShortInputException綾匯傚畠鏈変袱涓煙鈥斺攍ength鏄粰瀹氳緭鍏ョ殑闀垮害錛宎tleast鍒欐槸紼嬪簭
鏈熸湜鐨勬渶灝忛暱搴︺?br>鍦╡xcept浠庡彞涓紝鎴戜滑鎻愪緵浜嗛敊璇被鍜岀敤鏉ヨ〃紺洪敊璇?寮傚父瀵硅薄鐨勫彉閲忋傝繖涓庡嚱鏁拌皟鐢ㄤ腑鐨勫艦鍙?br>鍜屽疄鍙傛蹇電被浼箋傚湪榪欎釜鐗瑰埆鐨別xcept浠庡彞涓紝鎴戜滑浣跨敤寮傚父瀵硅薄鐨刲ength鍜宎tleast鍩熸潵涓虹敤鎴?br>鎵撳嵃涓涓伆褰撶殑娑堟伅銆?
]]>
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done
瀹冨浣曞伐浣?br>鎴戜滑鎶婃墍鏈夊彲鑳藉紩鍙戦敊璇殑璇彞鏀懼湪try鍧椾腑錛岀劧鍚庡湪except浠庡彞/鍧椾腑澶勭悊鎵鏈夌殑閿欒鍜屽紓甯搞?br>except浠庡彞鍙互涓撻棬澶勭悊鍗曚竴鐨勯敊璇垨寮傚父錛屾垨鑰呬竴緇勫寘鎷湪鍦嗘嫭鍙峰唴鐨勯敊璇?寮傚父銆傚鏋滄病鏈?br>緇欏嚭閿欒鎴栧紓甯哥殑鍚嶇О錛屽畠浼氬鐞?鎵鏈夌殑 閿欒鍜屽紓甯搞傚浜庢瘡涓猼ry浠庡彞錛岃嚦灝戦兘鏈変竴涓浉鍏?br>鑱旂殑except浠庡彞銆?br>濡傛灉鏌愪釜閿欒鎴栧紓甯告病鏈夎澶勭悊錛岄粯璁ょ殑Python澶勭悊鍣ㄥ氨浼氳璋冪敤銆傚畠浼氱粓姝㈢▼搴忕殑榪愯錛屽茍
涓旀墦鍗頒竴涓秷鎭紝鎴戜滑宸茬粡鐪嬪埌浜嗚繖鏍風殑澶勭悊銆?br>
]]>
#!/usr/bin/python
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
$ python pickling.py
['apple', 'mango', 'carrot']
瀹冨浣曞伐浣?/strong>
棣栧厛錛岃娉ㄦ剰鎴戜滑浣跨敤浜唅mport..as璇硶銆傝繖鏄竴縐嶄究鍒╂柟娉曪紝浠ヤ究浜庢垜浠彲浠ヤ嬌鐢ㄦ洿鐭殑妯″潡
鍚嶇О銆傚湪榪欎釜渚嬪瓙涓紝瀹冭繕璁╂垜浠兘澶熼氳繃綆鍗曞湴鏀瑰彉涓琛屽氨鍒囨崲鍒板彟涓涓ā鍧楋紙cPickle鎴栬?br>pickle錛夛紒鍦ㄧ▼搴忕殑鍏朵綑閮ㄥ垎鐨勬椂鍊欙紝鎴戜滑綆鍗曞湴鎶婅繖涓ā鍧楃О涓簆銆?br>涓轟簡鍦ㄦ枃浠墮噷鍌ㄥ瓨涓涓璞★紝棣栧厛浠ュ啓妯″紡鎵撳紑涓涓猣ile瀵硅薄錛岀劧鍚庤皟鐢ㄥ偍瀛樺櫒妯″潡鐨刣ump鍑?br>鏁幫紝鎶婂璞″偍瀛樺埌鎵撳紑鐨勬枃浠朵腑銆傝繖涓繃紼嬬О涓?鍌ㄥ瓨 銆?br>鎺ヤ笅鏉ワ紝鎴戜滑浣跨敤pickle妯″潡鐨刲oad鍑芥暟鐨勮繑鍥炴潵鍙栧洖瀵硅薄銆傝繖涓繃紼嬬О涓?鍙栧偍瀛?銆?
]]>
浠剁殑鎿嶄綔鐨勬椂鍊欙紝浣犺皟鐢╟lose鏂規硶鏉ュ憡璇塒ython鎴戜滑瀹屾垚浜嗗鏂囦歡鐨勪嬌鐢ㄣ?br>
#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
瀹冨浣曞伐浣?br>棣栧厛錛屾垜浠氳繃鎸囨槑鎴戜滑甯屾湜鎵撳紑鐨勬枃浠跺拰妯″紡鏉ュ垱寤轟竴涓猣ile綾葷殑瀹炰緥銆傛ā寮忓彲浠ヤ負璇繪ā寮?br>錛?r'錛夈佸啓妯″紡錛?w'錛夋垨榪藉姞妯″紡錛?a'錛夈備簨瀹炰笂榪樻湁澶氬緱澶氱殑妯″紡鍙互浣跨敤錛屼綘鍙互浣跨敤
help(file)鏉ヤ簡瑙e畠浠殑璇︽儏銆?br>鎴戜滑棣栧厛鐢ㄥ啓妯″紡鎵撳紑鏂囦歡錛岀劧鍚庝嬌鐢╢ile綾葷殑write鏂規硶鏉ュ啓鏂囦歡錛屾渶鍚庢垜浠敤close鍏抽棴榪欎釜鏂?br>浠躲?
]]>
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' % self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
杈撳嚭
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"
]]>
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % Person.population
def sayHi(self):
'''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
杈撳嚭
$ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
瀹冨浣曞伐浣?/strong>
榪欐槸涓涓緢闀跨殑渚嬪瓙錛屼絾鏄畠鏈夊姪浜庤鏄庣被涓庡璞$殑鍙橀噺鐨勬湰璐ㄣ傝繖閲岋紝population灞炰簬Person
綾伙紝鍥犳鏄竴涓被鐨勫彉閲忋俷ame鍙橀噺灞炰簬瀵硅薄錛堝畠浣跨敤self璧嬪鹼級鍥犳鏄璞$殑鍙橀噺銆?br>瑙傚療鍙互鍙戠幇__init__鏂規硶鐢ㄤ竴涓悕瀛楁潵鍒濆鍖朠erson瀹炰緥銆傚湪榪欎釜鏂規硶涓紝鎴戜滑璁﹑opulation
澧炲姞1錛岃繖鏄洜涓烘垜浠鍔犱簡涓涓漢銆傚悓鏍峰彲浠ュ彂鐜幫紝self.name鐨勫兼牴鎹瘡涓璞℃寚瀹氾紝榪欒〃
鏄庝簡瀹冧綔涓哄璞$殑鍙橀噺鐨勬湰璐ㄣ?br>璁頒綇錛屼綘鍙兘浣跨敤self鍙橀噺鏉ュ弬鑰冨悓涓涓璞$殑鍙橀噺鍜屾柟娉曘傝繖琚О涓?灞炴у弬鑰?銆?br>鍦ㄨ繖涓▼搴忎腑錛屾垜浠繕鐪嬪埌docstring瀵逛簬綾誨拰鏂規硶鍚屾牱鏈夌敤銆傛垜浠彲浠ュ湪榪愯鏃朵嬌鐢≒erson.
__doc__鍜孭erson.sayHi.__doc__鏉ュ垎鍒闂被涓庢柟娉曠殑鏂囨。瀛楃涓層?br>灝卞鍚宊_init__鏂規硶涓鏍鳳紝榪樻湁涓涓壒孌婄殑鏂規硶__del__錛屽畠鍦ㄥ璞℃秷閫濈殑鏃跺欒璋冪敤銆傚璞℃秷
閫濆嵆瀵硅薄涓嶅啀琚嬌鐢紝瀹冩墍鍗犵敤鐨勫唴瀛樺皢榪斿洖緇欑郴緇熶綔瀹冪敤銆傚湪榪欎釜鏂規硶閲岄潰錛屾垜浠彧鏄畝鍗?br>鍦版妸Person.population鍑?銆?br>褰撳璞′笉鍐嶈浣跨敤鏃訛紝__del__鏂規硶榪愯錛屼絾鏄緢闅句繚璇佽繖涓柟娉曠┒绔熷湪 浠涔堟椂鍊?榪愯銆傚鏋?br>浣犳兂瑕佹寚鏄庡畠鐨勮繍琛岋紝浣犲氨寰椾嬌鐢╠el璇彞錛屽氨濡傚悓鎴戜滑鍦ㄤ互鍓嶇殑渚嬪瓙涓嬌鐢ㄧ殑閭f牱銆?br>緇機++/Java/C#紼嬪簭鍛樼殑娉ㄩ噴
Python涓墍鏈夌殑綾繪垚鍛橈紙鍖呮嫭鏁版嵁鎴愬憳錛夐兘鏄?鍏叡鐨?錛屾墍鏈夌殑鏂規硶閮芥槸 鏈夋晥鐨?銆?br>鍙湁涓涓緥澶栵細濡傛灉浣犱嬌鐢ㄧ殑鏁版嵁鎴愬憳鍚嶇О浠?鍙屼笅鍒掔嚎鍓嶇紑 姣斿__privatevar錛孭ython鐨勫悕縐?br>綆$悊浣撶郴浼氭湁鏁堝湴鎶婂畠浣滀負縐佹湁鍙橀噺銆?br>榪欐牱灝辨湁涓涓儻渚嬶紝濡傛灉鏌愪釜鍙橀噺鍙兂鍦ㄧ被鎴栧璞′腑浣跨敤錛屽氨搴旇浠ュ崟涓嬪垝綰垮墠緙銆傝屽叾浠栫殑
鍚嶇О閮藉皢浣滀負鍏叡鐨勶紝鍙互琚叾浠栫被/瀵硅薄浣跨敤銆傝浣忚繖鍙槸涓涓儻渚嬶紝騫朵笉鏄疨ython鎵瑕佹眰
鐨勶紙涓庡弻涓嬪垝綰垮墠緙涓嶅悓錛夈?br>鍚屾牱錛屾敞鎰廮_del__鏂規硶涓?destructor 鐨勬蹇電被浼箋?
]]>
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
# This short example can also be written as Person('Swaroop').sayHi()
$ python class_init.py
Hello, my name is Swaroop
瀹冨浣曞伐浣?br>榪欓噷錛屾垜浠妸__init__鏂規硶瀹氫箟涓哄彇涓涓弬鏁皀ame錛堜互鍙婃櫘閫氱殑鍙傛暟self錛夈傚湪榪欎釜__init__閲岋紝
鎴戜滑鍙槸鍒涘緩涓涓柊鐨勫煙錛屼篃縐頒負name銆傛敞鎰忓畠浠槸涓や釜涓嶅悓鐨勫彉閲忥紝灝界瀹冧滑鏈夌浉鍚岀殑鍚?br>瀛椼傜偣鍙蜂嬌鎴戜滑鑳藉鍖哄垎瀹冧滑銆?br>鏈閲嶈鐨勬槸錛屾垜浠病鏈変笓闂ㄨ皟鐢╛_init__鏂規硶錛屽彧鏄湪鍒涘緩涓涓被鐨勬柊瀹炰緥鐨勬椂鍊欙紝鎶婂弬鏁板寘
鎷湪鍦嗘嫭鍙峰唴璺熷湪綾誨悕鍚庨潰錛屼粠鑰屼紶閫掔粰__init__鏂規硶銆傝繖鏄繖縐嶆柟娉曠殑閲嶈涔嬪銆?br>鐜板湪錛屾垜浠兘澶熷湪鎴戜滑鐨勬柟娉曚腑浣跨敤self.name鍩熴傝繖鍦╯ayHi鏂規硶涓緱鍒頒簡楠岃瘉銆?
]]>
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass # An empty block
p = Person()
print p
杈撳嚭
$ python simplestclass.py
<__main__.Person instance at 0xf6fcb18c>
鎴戜滑浣跨敤class璇彞鍚庤窡綾誨悕錛屽垱寤轟簡涓涓柊鐨勭被銆傝繖鍚庨潰璺熺潃涓涓緝榪涚殑璇彞鍧楀艦鎴愮被浣撱傚湪
榪欎釜渚嬪瓙涓紝鎴戜滑浣跨敤浜嗕竴涓┖鐧藉潡錛屽畠鐢眕ass璇彞琛ㄧず銆?br>鎺ヤ笅鏉ワ紝鎴戜滑浣跨敤綾誨悕鍚庤窡涓瀵瑰渾鎷彿鏉ュ垱寤轟竴涓璞?瀹炰緥銆備負浜嗛獙璇侊紝鎴戜滑綆鍗曞湴鎵撳嵃浜嗚繖
涓彉閲忕殑綾誨瀷銆傚畠鍛婅瘔鎴戜滑鎴戜滑宸茬粡鍦╛_main__妯″潡涓湁浜嗕竴涓狿erson綾葷殑瀹炰緥銆?br>鍙互娉ㄦ剰鍒板瓨鍌ㄥ璞$殑璁$畻鏈哄唴瀛樺湴鍧涔熸墦鍗頒簡鍑烘潵銆傝繖涓湴鍧鍦ㄤ綘鐨勮綆楁満涓婁細鏄彟澶栦竴涓?br>鍊鹼紝鍥犱負Python鍙互鍦ㄤ換浣曠┖浣嶅瓨鍌ㄥ璞°?
]]>
#!/usr/bin/python
# Filename: str_methods.py
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'
if 'a' in name:
print 'Yes, it contains the string "a"'
if name.find('war') != -1:
print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)
杈撳嚭
$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
瀹冨浣曞伐浣?/strong>
榪欓噷錛屾垜浠湅鍒頒嬌鐢ㄤ簡璁稿瀛楃涓叉柟娉曘?span style="COLOR: red">startwith鏂規硶鏄敤鏉ユ祴璇曞瓧絎︿覆鏄惁浠ョ粰瀹氬瓧絎︿覆寮
濮嬨?span style="COLOR: red">in鎿嶄綔絎︾敤鏉ユ楠屼竴涓粰瀹氬瓧絎︿覆鏄惁涓哄彟涓涓瓧絎︿覆鐨勪竴閮ㄥ垎銆?br>find鏂規硶鐢ㄦ潵鎵懼嚭緇欏畾瀛楃涓插湪鍙︿竴涓瓧絎︿覆涓殑浣嶇疆錛屾垨鑰呰繑鍥?1浠ヨ〃紺烘壘涓嶅埌瀛愬瓧絎︿覆銆?br>str綾諱篃鏈変互涓涓綔涓哄垎闅旂鐨勫瓧絎︿覆join搴忓垪鐨勯」鐩殑鏁存磥鐨勬柟娉曪紝瀹冭繑鍥炰竴涓敓鎴愮殑澶у瓧絎?br>涓層?
]]>
瀹氥?br>
#!/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
$ 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']
浣犻渶瑕佽浣忕殑鍙槸濡傛灉浣犳兂瑕佸鍒朵竴涓垪琛ㄦ垨鑰呯被浼肩殑搴?br>鍒楁垨鑰呭叾浠栧鏉傜殑瀵硅薄錛堜笉鏄鏁存暟閭f牱鐨勭畝鍗?瀵硅薄 錛夛紝閭d箞浣犲繀欏諱嬌鐢ㄥ垏鐗囨搷浣滅鏉ュ彇寰?br>鎷瘋礉銆傚鏋滀綘鍙槸鎯寵浣跨敤鍙︿竴涓彉閲忓悕錛屼袱涓悕縐伴兘 寮曠敤 鍚屼竴涓璞★紝閭d箞濡傛灉浣犱笉灝忓績
鐨勮瘽錛屽彲鑳戒細寮曟潵鍚勭楹葷儲銆?
]]>
#!/usr/bin/python
# Filename: seq.py
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]
$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
瀹冨浣曞伐浣?/strong>
棣栧厛錛屾垜浠潵瀛︿範濡備綍浣跨敤绱㈠紩鏉ュ彇寰楀簭鍒椾腑鐨勫崟涓」鐩傝繖涔熻縐頒綔鏄笅鏍囨搷浣溿傛瘡褰撲綘鐢?br>鏂規嫭鍙蜂腑鐨勪竴涓暟鏉ユ寚瀹氫竴涓簭鍒楃殑鏃跺欙紝Python浼氫負浣犳姄鍙栧簭鍒椾腑瀵瑰簲浣嶇疆鐨勯」鐩傝浣忥紝
Python浠?寮濮嬭鏁般傚洜姝わ紝shoplist[0]鎶撳彇絎竴涓」鐩紝shoplist[3]鎶撳彇shoplist搴忓垪涓殑絎洓涓?br>鍏冪礌銆?br>绱㈠紩鍚屾牱鍙互鏄礋鏁幫紝鍦ㄩ偅鏍風殑鎯呭喌涓嬶紝浣嶇疆鏄粠搴忓垪灝懼紑濮嬭綆楃殑銆?/span>鍥犳錛宻hoplist[-1]琛ㄧず
搴忓垪鐨勬渶鍚庝竴涓厓绱犺宻hoplist[-2]鎶撳彇搴忓垪鐨勫掓暟絎簩涓」鐩?br>鍒囩墖鎿嶄綔絎︽槸搴忓垪鍚嶅悗璺熶竴涓柟鎷彿錛屾柟鎷彿涓湁涓瀵瑰彲閫夌殑鏁板瓧錛屽茍鐢ㄥ啋鍙峰垎鍓層傛敞鎰忚繖涓?br>浣犱嬌鐢ㄧ殑绱㈠紩鎿嶄綔絎﹀崄鍒嗙浉浼箋?span style="COLOR: red">璁頒綇鏁版槸鍙夌殑錛岃屽啋鍙鋒槸蹇呴』鐨勩?/span>
鍒囩墖鎿嶄綔絎︿腑鐨勭涓涓暟錛堝啋鍙蜂箣鍓嶏級琛ㄧず鍒囩墖寮濮嬬殑浣嶇疆錛岀浜屼釜鏁幫紙鍐掑彿涔嬪悗錛夎〃紺哄垏鐗?br>鍒板摢閲岀粨鏉熴傚鏋滀笉鎸囧畾絎竴涓暟錛孭ython灝變粠搴忓垪棣栧紑濮嬨傚鏋滄病鏈夋寚瀹氱浜屼釜鏁幫紝鍒?br>Python浼氬仠姝㈠湪搴忓垪灝俱傛敞鎰忥紝榪斿洖鐨勫簭鍒椾粠寮濮嬩綅緗?寮濮?錛屽垰濂藉湪 緇撴潫 浣嶇疆涔嬪墠緇撴潫銆傚嵆
寮濮嬩綅緗槸鍖呭惈鍦ㄥ簭鍒楀垏鐗囦腑鐨勶紝鑰岀粨鏉熶綅緗鎺掓枼鍦ㄥ垏鐗囧銆?br>榪欐牱錛宻hoplist[1:3]榪斿洖浠庝綅緗?寮濮嬶紝鍖呮嫭浣嶇疆2錛屼絾鏄仠姝㈠湪浣嶇疆3鐨勪竴涓簭鍒楀垏鐗囷紝鍥犳榪?br>鍥炰竴涓惈鏈変袱涓」鐩殑鍒囩墖銆傜被浼煎湴錛宻hoplist[:]榪斿洖鏁翠釜搴忓垪鐨勬嫹璐濄?br>浣犲彲浠ョ敤璐熸暟鍋氬垏鐗囥傝礋鏁扮敤鍦ㄤ粠搴忓垪灝懼紑濮嬭綆楃殑浣嶇疆銆備緥濡傦紝shoplist[:-1]浼氳繑鍥為櫎浜嗘渶鍚?br>涓涓」鐩鍖呭惈鎵鏈夐」鐩殑搴忓垪鍒囩墖銆?br>浣跨敤Python瑙i噴鍣ㄤ氦浜掑湴灝濊瘯涓嶅悓鍒囩墖鎸囧畾緇勫悎錛屽嵆鍦ㄦ彁紺虹涓嬩綘鑳藉椹笂鐪嬪埌緇撴灉銆傚簭鍒楃殑
紲炲涔嬪鍦ㄤ簬浣犲彲浠ョ敤鐩稿悓鐨勬柟娉曡闂厓緇勩佸垪琛ㄥ拰瀛楃涓層?
]]>
鍙峰垎鍓詫紝鑰屽悇涓鐢ㄩ楀彿鍒嗗壊錛屾墍鏈夎繖浜涢兘鍖呮嫭鍦ㄨ姳鎷彿涓?br>璁頒綇瀛楀吀涓殑閿?鍊煎鏄病鏈夐『搴忕殑銆傚鏋滀綘鎯寵涓涓壒瀹氱殑欏哄簭錛岄偅涔堜綘搴旇鍦ㄤ嬌鐢ㄥ墠鑷繁
瀵瑰畠浠帓搴忋?br>瀛楀吀鏄痙ict綾葷殑瀹炰緥/瀵硅薄銆?br>
#!/usr/bin/python
# Filename: using_dict.py
# 'ab' is short for 'a'ddress'b'ook
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
print "Swaroop's address is %s" % ab['Swaroop']
# Adding a key/value pair
ab['Guido'] = 'guido@python.org'
# Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
print 'Contact %s at %s' % (name, address)
if 'Guido' in ab: # OR ab.has_key('Guido')
print "\nGuido's address is %s" % ab['Guido']
$ python using_dict.py
Swaroop's address is swaroopch@byteofpython.info
There are 4 contacts in the address-book
Contact Swaroop at swaroopch@byteofpython.info
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Contact Guido at guido@python.org
Guido's address is guido@python.org
]]>
#!/usr/bin/python
# Filename: using_tuple.py
zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]
$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
鍚湁0涓垨1涓」鐩殑鍏冪粍銆備竴涓┖鐨勫厓緇勭敱涓瀵圭┖鐨勫渾鎷彿緇勬垚錛屽myempty = ()銆傜劧鑰岋紝鍚?br>鏈夊崟涓厓绱犵殑鍏冪粍灝變笉閭d箞綆鍗曚簡銆備綘蹇呴』鍦ㄧ涓涓紙鍞竴涓涓級欏圭洰鍚庤窡涓涓楀彿錛岃繖鏍?br>Python鎵嶈兘鍖哄垎鍏冪粍鍜岃〃杈懼紡涓竴涓甫鍦嗘嫭鍙風殑瀵硅薄銆傚嵆濡傛灉浣犳兂瑕佺殑鏄竴涓寘鍚」鐩?鐨勫厓
緇勭殑鏃跺欙紝浣犲簲璇ユ寚鏄巗ingleton = (2 , )銆?br>
鍏冪粍涓庢墦鍗拌鍙?br>
#!/usr/bin/python
# Filename: print_tuple.py
age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name
杈撳嚭
$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?
]]>
涓垪琛紝浣犲彲浠ユ坊鍔犮佸垹闄ゆ垨鏄悳绱㈠垪琛ㄤ腑鐨勯」鐩傜敱浜庝綘鍙互澧炲姞鎴栧垹闄ら」鐩紝鎴戜滑璇村垪琛?br>鏄?鍙彉鐨?鏁版嵁綾誨瀷錛屽嵆榪欑綾誨瀷鏄彲浠ヨ鏀瑰彉鐨勩?br>
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist
$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
娉ㄦ剰錛屾垜浠湪print璇彞鐨勭粨灝句嬌鐢ㄤ簡涓涓?閫楀彿 鏉ユ秷闄ゆ瘡涓猵rint璇彞鑷姩鎵撳嵃鐨勬崲琛岀銆傝繖鏍?br>鍋氭湁鐐歸毦鐪嬶紝涓嶈繃紜疄綆鍗曟湁鏁堛?/span>
]]>
]]>
$ python
>>> import sys
>>> dir(sys) # get list of attributes for sys module
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type',
'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval',
'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding',
'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache',
'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
'version', 'version_info', 'warnoptions']
>>> dir() # get list of attributes for current module
['__builtins__', '__doc__', '__name__', 'sys']
>>>
>>> a = 5 # create a new variable 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # delete/remove a name
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
]]>
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print 'Hi, this is mymodule speaking.'
version = '0.1'
# End of mymodule.py
璁頒綇榪欎釜妯″潡搴旇琚斁緗湪鎴戜滑杈撳叆瀹冪殑紼嬪簭鐨勫悓涓涓洰褰曚腑錛屾垨鑰呭湪sys.path鎵鍒楃洰褰曚箣涓銆?br>
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print 'Version', mymodule.version
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
涓嬮潰鏄竴涓嬌鐢╢rom..import璇硶鐨勭増鏈?/strong>
#!/usr/bin/python
# Filename: mymodule_demo2.py
from mymodule import sayhi, version
# Alternative:
# from mymodule import *
sayhi()
print 'Version', version
]]>