python 学习 DAY9笔记

34 Packages

  • 将相关的module 放在一个package中。


    Molish's courseware
  • package--module--function(明确该层次关系,很重要)

  • 创建一个package
    在目录中(new directory)放置一个文件init.py,python即会将这个文件夹视为一个package。
    ps:直接创建Python Package 也是一个directory 底下有个init.py文件。

  • 创立package
  • 创建module,shipping
  • module内构建函数
def cal_shipping():
    print('cal_shipping')


def tax_shipping():
    print('tax_shipping')

  • 调用package
from ecommerce import shipping
shipping.tax_shipping()
shipping.cal_shipping()

35 Generating Random Values


random modules

  • 首先import random(自建module)
  1. random
random.random()
##返回随机数范围0-1
  1. randint
random.randint(10,20)
##返回整数范围10-20
  1. choice
numbers = ['a','b','c','d']
random.choice(numbers)
##返回整数范围10-20
  • 创建一个类Dice,类中def 一个function roll.并且每次调用roll,会返回一个元组(x,y)实现骰子的功能。
import random


class Dice:
    def roll(self):
        x = random.randint(1, 6)
        y = random.randint(1, 6)
        return x, y ##python会自动将一对数字默认为元组


dice = Dice()
print(dice.roll())
  • PEP-8 是python一个规范。很多规范并不影响语句的实现,但优秀的coder 会规范化他们的code。

36 Files and Directories (part1)

  • 通过python 查找并管理文件与目录
  • Absolute path
    从根目录开始算,去其他位置。


' \ '反斜杠
' / '斜杠

  • relative path
    从当前位置,去其他的位置。

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
  1. exists
    查看目录是否存在
path = Path("ecommerce")
print(path.exists())
# 返回True(我们有这个目录)
path = Path('emails')
print(path.exists())
# 返回False(我们没有这个目录)
  1. mkdir
    创建新目录(默认相对目录下)
path = Path('emails')
path.mkdir()
# 创建目录emails
  1. rmdir
    删除目录(默认相对目录下)
path = Path('emails')
path.rmdir()
# 删除目录emails

小感想002

  • 对于类来说,可以对类设定不同的attributes,例如通过__int__(self,xxx,xxx)
    设定如xxx这样的parameter
    再通过def 相关的function(self)
    在function 中加入相关parameter,如self.xxx
    接着便可以在语句中调用类,通过外部给予相应参数。实现外部信息的输入。

  • 但如果这样考虑功能。单纯使用def function(xxx)
    如下

def greet_user(name):
    print(f"Hello,{name}")
    print("Welcome.")


name_user = input('What is ur name? ')
greet_user(name_user)

也可以实现外部信息的交互(行参占位,实参录入)。

那么Class作为图纸的意义如何体现呢?

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容