• Python将函数放入模块


    函数可以将通用的代码封装起来,便于其他程序或者方法调用。将函数存放在文件中,这个文件被称为模块。将函数存储在独立的模块中,可与其他程序员共享这些文件而不是整个程序。

    fun.py

    def say_hi(name):
        print(name+" say hi.")
    
    def getDouble(num):
        return num*2
    
    def doSomething():
        return "doing"

    一、导入整个模块

    my.py中导入fun模块,并通过模块名.调用其say_hi方法

    import fun 
    
    fun.say_hi('xiao')

    二、导入特定的函数

    from fun import say_hi
    
    say_hi('xiao')

    三、导入模块中多个函数

    多个函数用逗号分隔

    from fun import say_hi,getDouble
    
    say_hi('xiao')
    num=getDouble(2)
    print(num)

    四、导入模块中的所有函数

    这种方式在导入时比较省事,使用*代替了所有函数,阅读性很差,不建议这么写。建议要么明确写出导入的函数,要么导入整个模块

    from fun import *
    
    say_hi('xiao')
    num=getDouble(2)
    print(num)

    五、使用as给导入的函数、模块指定别名

     指定别名使用关键字as

    1、给函数指定别名

    from fun import say_hi as hi
    
    hi('xiao')

    2、给模块指定别名

    import fun as f
    
    f.say_hi('xiao')
    num=f.getDouble(3)
    print(num)

  • 相关阅读:
    Kth Ancestor 第k个祖先问题
    centOS 6.4挂载centOS分区
    上阶段学习总结
    code testing
    Helo~
    leetcode--Maximum Subarray
    leetcode--Climbing Stairs
    leetcode--Search Insert Position
    leetcode--Best Time to Buy and Sell Stock III
    leetcode--Best Time to Buy and Sell Stock II
  • 原文地址:https://www.cnblogs.com/qq931399960/p/11111217.html
Copyright © 2020-2023  润新知