Python-Modules and Packages

module function class difference

Ex:The Python script game.py will implement the game. It will use the function draw_game from the file draw.py, or in other words, thedraw module, that implements the logic for drawing the game on the screen.

几种调用draw_game function的方法or调用draw module 中 draw_function 的方法
一:

# game.py
# import the draw module
import draw

def play_game():
    ...

def main():
    result = play_game()
    draw.draw_game(result)

# this means that if this script is executed, then 
# main() will be executed
if __name__ == '__main__':
    main()

–Import draw module and use the its function draw_game.
–In this module, using the dot operator to specify in which module the function is implemented.

二:

# game.py
# import the draw module
from draw import draw_game

def main():
    result = play_game()
    draw_game(result)

–We may also import the function draw_game directly into the main script’s namespace, by using the from command.
–The advantages of using this notation is that it is easier to use the functions inside the current module because you don’t need to specify which module the function comes from. However, any namespace cannot have two objects with the exact same name, so the import command may replace an existing object in the namespace.

三:
We may also use the import * command to import all objects from a specific module, like this:

# game.py
# import the draw module
from draw import *

def main():
    result = play_game()
    draw_game(result)

–This might be a bit risky as changes in the module might affect the module which imports it, but it is shorter and also does not require you to specify which objects you wish to import from the module.
Because any namespace cannot have two objects with the exact same name, import * may import some same name objets and make confusion.

四:

import foo.bar
from foo import bar

In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don’t, because we import the module to our module’s namespace.

If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the init.py file inside the foo directory.

参考https://www.learnpython.org/en/Modules_and_Packages

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值