#使用模塊
##使用sys
1.代碼
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test module '
__author__ = 'Bernicechl'
import sys
def test():
args = sys.argv
if len(args)==1:
print('Hello, world!')
elif len(args)==2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments!')
if __name__=='__main__':
test()
若出現報錯
>>> python module.py
File "<stdin>", line 1
python module.py
^
SyntaxError: invalid syntax
則說明沒有跳出python交互環境,要退出交互環境再操作
(1)sys模塊有一個argv變量,用list存儲了命令行的所有參數。argv至少有一個元素,因爲第一個參數永遠是該.py文件的名稱
運行python module.py獲得的sys.argv就是[‘module.py’];
如運行
python module.py Bernicechl
則輸出
Hello, Bernicechl!
獲得的sys.argv就是
['module.py', Bernice'l]
2.當我們在命令行運行module模塊文件時,Python解釋器把一個特殊變量__name__置爲__main__,而如果在其他地方導入該hello模塊時,if判斷將失敗,因此,這種if測試可以讓一個模塊通過命令行運行時執行一些額外的代碼,最常見的就是運行測試。
如果啓動Python交互環境,再導入module
模塊(文件名)
即>>> import hello
導入時,沒有打印Hello, word!,因爲沒有執行test()函數。
調用module.test()時,才能打印出Hello, word!
即module.test()
#類
##類的實例
1.簡單代碼
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
def __init__(self,name,score):
self.name = name
self.score = score
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
lisa = Student('Lisa', 99)
bart = Student('Bart', 59)
print(lisa.name, lisa.get_grade())
print(bart.name, bart.get_grade())
ps:__init__
的下劃線德有兩個!
2.如果要讓內部屬性不被外部訪問,可以把屬性的名稱前加上兩個下劃線__,在Python中,實例的變量名如果以__開頭,就變成了一個私有變量(private),只有內部可以訪問,外部不能訪問
即:
self._name = name
self._score = score
3.注意下面的這種錯誤寫法:
>>> bart = Student('Bart Simpson', 59)
>>> bart.get_name()
'Bart Simpson'
>>> bart.__name = 'New Name' # 設置__name變量!
>>> bart.__name
'New Name'
表面上看,外部代碼“成功”地設置了__name
變量,但實際上這個__name
變量和class內部的__name
變量不是一個變量!內部的__name
變量已經被Python解釋器自動改成了_Student__name
,而外部代碼給bart新增了一個__name
變量。不信試試:
>>> bart.get_name() # get_name()內部返回self.__name
'Bart Simpson'
4.實例
類屬性和實例屬性其實是兩個不同的對象,因爲在將類Student賦值給s時,其實s就好像是Student類的一個子類,繼承Student的全部,因爲他們的內存地址並不是指向同一個位置
>>> class Student(object):
name = 'Student'
>>> s=Student()
>>> id(Student)
42362760
>>> id(s)
45692856