34 Packages
-
將相關(guān)的module 放在一個package中啸臀。
Molish's courseware package--module--function(明確該層次關(guān)系,很重要)
- 創(chuàng)建一個package
在目錄中(new directory)放置一個文件init.py,python即會將這個文件夾視為一個package枚碗。
ps:直接創(chuàng)建Python Package 也是一個directory 底下有個init.py文件。
- 創(chuàng)立package
- 創(chuàng)建module,shipping
- module內(nèi)構(gòu)建函數(shù)
def cal_shipping():
print('cal_shipping')
def tax_shipping():
print('tax_shipping')
- 調(diào)用package
from ecommerce import shipping
shipping.tax_shipping()
shipping.cal_shipping()
35 Generating Random Values
python內(nèi)部有很多自建的modules
datetime, email...
可以從這個網(wǎng)址查閱到
https://docs.python.org/3.3/py-modindex.html-
這里可以看到許多python自建的modules
random modules
- 首先
import random
(自建module)
- random
random.random()
##返回隨機數(shù)范圍0-1
- randint
random.randint(10,20)
##返回整數(shù)范圍10-20
- choice
numbers = ['a','b','c','d']
random.choice(numbers)
##返回整數(shù)范圍10-20
- 創(chuàng)建一個類Dice迁酸,類中def 一個function roll.并且每次調(diào)用roll炸宵,會返回一個元組(x,y)實現(xiàn)骰子的功能。
import random
class Dice:
def roll(self):
x = random.randint(1, 6)
y = random.randint(1, 6)
return x, y ##python會自動將一對數(shù)字默認為元組
dice = Dice()
print(dice.roll())
- PEP-8 是python一個規(guī)范君纫。很多規(guī)范并不影響語句的實現(xiàn)驯遇,但優(yōu)秀的coder 會規(guī)范化他們的code。
36 Files and Directories (part1)
- 通過python 查找并管理文件與目錄
-
Absolute path
從根目錄開始算蓄髓,去其他位置叉庐。
' \ '反斜杠
' / '斜杠
- relative path
從當(dāng)前位置,去其他的位置会喝。
ps:第一次沒有任何PEP-8 warning的代碼
from pathlib import Path # 類
path = Path("ecommerce")
print(path.exists())
# 返回True(我們有這個目錄)
path = Path('emails')
print(path.exists())
# 返回False(我們沒有這個目錄)
- 首先引入
from pathlib import Path
- exists
查看目錄是否存在
path = Path("ecommerce")
print(path.exists())
# 返回True(我們有這個目錄)
path = Path('emails')
print(path.exists())
# 返回False(我們沒有這個目錄)
- mkdir
創(chuàng)建新目錄(默認相對目錄下)
path = Path('emails')
path.mkdir()
# 創(chuàng)建目錄emails
- rmdir
刪除目錄(默認相對目錄下)
path = Path('emails')
path.rmdir()
# 刪除目錄emails
小感想002
對于類來說陡叠,可以對類設(shè)定不同的attributes,例如通過
__int__(self,xxx,xxx)
設(shè)定如xxx這樣的parameter
再通過def 相關(guān)的function(self)
在function 中加入相關(guān)parameter,如self.xxx
接著便可以在語句中調(diào)用類肢执,通過外部給予相應(yīng)參數(shù)枉阵。實現(xiàn)外部信息的輸入。但如果這樣考慮功能蔚万。單純使用
def function(xxx)
如下
def greet_user(name):
print(f"Hello,{name}")
print("Welcome.")
name_user = input('What is ur name? ')
greet_user(name_user)
也可以實現(xiàn)外部信息的交互(行參占位岭妖,實參錄入)。
那么Class作為圖紙的意義如何體現(xiàn)呢反璃?