zoukankan      html  css  js  c++  java
  • python模块

     https://study.163.com/course/courseMain.htm?courseId=1006383008&share=2&shareId=400000000398149(博主录制)

    (原创声明,转载引用需要指明来源)

    模块概述

    Python 模块(Module),是一个文件,用 .py 结尾。模块包含了 Python 对象定义和Python语句。模块能够有逻辑地组织 Python 代码段,把相关的代码分配到一个模块里能让开发人员的代码更好用,更易懂。模块能定义函数,类和变量,模块里也能包含可执行的代码。

    下例是个简单的模块 simpleModule.py:

    # -*- coding: utf-8 -*-
    """
    最简单的模块
    """
    def PrintName(name): #定义一个函数
        print("hello:",name)#输出信息
    

    导入模块三种形式

    只有导入模块后才能使用。导入有多种方法,每种方法对名称空间都有不同的影响。

    模块引入形式主要有三种形式,用math模块为例,分别如下:

    (1) import math(推荐)

    这是进行导入的最简单方法,通常建议这样做。您可以使用模块名称作为前缀来访问模块的名称空间。这意味着您可以在程序中使用与模块中相同的名称,但可以同时使用它们。当您导入多个模块时,就可以清晰辨别特定名称属于哪个模块。

    import math      #导入math模块
    a=10             #创建变量a,赋值10
    b=math.sqrt(a)   #对变量a取平方根
    print(b)         #输出变量b值
    

    (2)from math import sqrt

    这会将名称(或几个名称,用逗号分隔)直接从模块的名称空间导入程序的名称空间。要使用导入的名称,您不再需要使用前缀,而只需直接使用名称。如果您确定只需要使用几个名称,这将很有用。缺点是您无法在自己的程序中将导入的名称用于其他名称。例如,您可以使用add()代替Integer.add(),但是如果您的程序具有add()函数,则您将无法访问Integer的add()函数。

    from math import sqrt  #从math模块导入sqrt方法
    a=10                   #创建变量a,赋值10
    b=sqrt(a)              #对变量a取平方根
    print(b)               #输出变量b值
    

    (3)from math import*

    这会将所有名称从math直接导入到模块的名称空间中。通常这不是一个好主意,因为它会导致“名称空间污染”。如果您发现自己在代码中编写此代码,则最好使用第一种导入类型。

    这些导入与功能一样,也适用于类和其他数据。导入可能会对它们对名称空间的影响造成混淆。这种方式可以让代码更加整洁,但需要倍加注意名称空间混乱的问题。

    from math import*  #从math模块导入所有名称
    a=10                   #创建变量a,赋值10
    b=sqrt(a)              #对变量a取平方根
    print(b)               #输出变量b值
    

    dir()函数

    dir() 函数一个排好序的字符串列表,contents是一个模块里定义过的名字。

    返回的列表容纳了在一个模块里定义的所有模块,变量和函数。如下一个简单的实例

    import math         #导入math模块
    contents=dir(math)  #把math模块包含对象保存到变量contents
    print(contents)     #输出math模块包含对象
    

    Contents返回列表如下:

    ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
    'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
    'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf',
    'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

    help()函数

    help() 函数用于查看函数或模块用途的详细说明。例如我们想查看math模块是干啥用的,

    就用help(math),下图中描述了math是python内置模块,是用于访问数学函数的。Math模块的函数也一一说明用途。

    help(math)  #查看math模块用途的详细说明
    Help on built-in module math:
    
    NAME
        math
    
    DESCRIPTION
        This module provides access to the mathematical functions
        defined by the C standard.
    
    FUNCTIONS
        acos(x, /)
            Return the arc cosine (measured in radians) of x.
        
        acosh(x, /)
            Return the inverse hyperbolic cosine of x.
        
        asin(x, /)
            Return the arc sine (measured in radians) of x.
        
        asinh(x, /)
            Return the inverse hyperbolic sine of x.
        
        atan(x, /)
            Return the arc tangent (measured in radians) of x.
        
        atan2(y, x, /)
            Return the arc tangent (measured in radians) of y/x.
            
            Unlike atan(y/x), the signs of both x and y are considered.
        
        atanh(x, /)
            Return the inverse hyperbolic tangent of x.
        
        ceil(x, /)
            Return the ceiling of x as an Integral.
            
            This is the smallest integer >= x.
        
        copysign(x, y, /)
            Return a float with the magnitude (absolute value) of x but the sign of y.
            
            On platforms that support signed zeros, copysign(1.0, -0.0)
            returns -1.0.
        
        cos(x, /)
            Return the cosine of x (measured in radians).
        
        cosh(x, /)
            Return the hyperbolic cosine of x.
        
        degrees(x, /)
            Convert angle x from radians to degrees.
        
        erf(x, /)
            Error function at x.
        
        erfc(x, /)
            Complementary error function at x.
        
        exp(x, /)
            Return e raised to the power of x.
        
        expm1(x, /)
            Return exp(x)-1.
            
            This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
        
        fabs(x, /)
            Return the absolute value of the float x.
        
        factorial(x, /)
            Find x!.
            
            Raise a ValueError if x is negative or non-integral.
        
        floor(x, /)
            Return the floor of x as an Integral.
            
            This is the largest integer <= x.
        
        fmod(x, y, /)
            Return fmod(x, y), according to platform C.
            
            x % y may differ.
        
        frexp(x, /)
            Return the mantissa and exponent of x, as pair (m, e).
            
            m is a float and e is an int, such that x = m * 2.**e.
            If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
        
        fsum(seq, /)
            Return an accurate floating point sum of values in the iterable seq.
            
            Assumes IEEE-754 floating point arithmetic.
        
        gamma(x, /)
            Gamma function at x.
        
        gcd(x, y, /)
            greatest common divisor of x and y
        
        hypot(x, y, /)
            Return the Euclidean distance, sqrt(x*x + y*y).
        
        isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
            Determine whether two floating point numbers are close in value.
            
              rel_tol
                maximum difference for being considered "close", relative to the
                magnitude of the input values
              abs_tol
                maximum difference for being considered "close", regardless of the
                magnitude of the input values
            
            Return True if a is close in value to b, and False otherwise.
            
            For the values to be considered close, the difference between them
            must be smaller than at least one of the tolerances.
            
            -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
            is, NaN is not close to anything, even itself.  inf and -inf are
            only close to themselves.
        
        isfinite(x, /)
            Return True if x is neither an infinity nor a NaN, and False otherwise.
        
        isinf(x, /)
            Return True if x is a positive or negative infinity, and False otherwise.
        
        isnan(x, /)
            Return True if x is a NaN (not a number), and False otherwise.
        
        ldexp(x, i, /)
            Return x * (2**i).
            
            This is essentially the inverse of frexp().
        
        lgamma(x, /)
            Natural logarithm of absolute value of Gamma function at x.
        
        log(...)
            log(x, [base=math.e])
            Return the logarithm of x to the given base.
            
            If the base not specified, returns the natural logarithm (base e) of x.
        
        log10(x, /)
            Return the base 10 logarithm of x.
        
        log1p(x, /)
            Return the natural logarithm of 1+x (base e).
            
            The result is computed in a way which is accurate for x near zero.
        
        log2(x, /)
            Return the base 2 logarithm of x.
        
        modf(x, /)
            Return the fractional and integer parts of x.
            
            Both results carry the sign of x and are floats.
        
        pow(x, y, /)
            Return x**y (x to the power of y).
        
        radians(x, /)
            Convert angle x from degrees to radians.
        
        remainder(x, y, /)
            Difference between x and the closest integer multiple of y.
            
            Return x - n*y where n*y is the closest integer multiple of y.
            In the case where x is exactly halfway between two multiples of
            y, the nearest even value of n is used. The result is always exact.
        
        sin(x, /)
            Return the sine of x (measured in radians).
        
        sinh(x, /)
            Return the hyperbolic sine of x.
        
        sqrt(x, /)
            Return the square root of x.
        
        tan(x, /)
            Return the tangent of x (measured in radians).
        
        tanh(x, /)
            Return the hyperbolic tangent of x.
        
        trunc(x, /)
            Truncates the Real x to the nearest Integral toward 0.
            
            Uses the __trunc__ magic method.
    
    DATA
        e = 2.718281828459045
        inf = inf
        nan = nan
        pi = 3.141592653589793
        tau = 6.283185307179586
    
    FILE
        (built-in)
    

    我们也可以用help()函数查看math模块里某个函数用法,例如输入help(math.sqrt)。下图显示该函数返回一个数的平方根。

    help(math.sqrt) #查看math模块里sqrt函数用法
    Help on built-in function sqrt in module math:
    
    sqrt(x, /)
        Return the square root of x.
    

    函数命名空间

    (1)命名空间本质--字典

    变量是映射到对象的名称(标识符)。名称空间是变量名(键)及其对应对象(值)的字典。

    Python语句可以访问本地名称空间和全局名称空间中的变量。如果局部变量和全局变量具有相同的名称,则局部变量将覆盖全局变量。

    每个函数都有其自己的本地名称空间。类方法遵循与普通函数相同的作用域规则。

    Python对变量是局部变量还是全局变量进行了有根据的猜测。假定在函数中分配了任何值的任何变量都是局部变量。

    因此,为了向函数内的全局变量分配值,必须首先使用global语句。

    语句global VarName告诉Python VarName是全局变量。 Python停止在本地名称空间中搜索变量。

    例如,我们在全局名称空间中定义一个变量Money。在功能Money中,我们为Money指定一个值。因此,Python假定Money是局部变量。但是,我们在设置之前访问了局部变量Money的值,因此结果为UnboundLocalError。取消注释全局语句即可解决该问题。

    (2)Python有多个命名空间

    对于Python,可能有多个名称空间可用于确定与变量关联的对象。
    请记住,名称空间是名称和对象的关联。

    例如宇宙,不同星球是不同命名空间。即使不同星球存在相同人名,但也是不同的人。函数也是一样,即使名字一样,但不同函数对象是不一样的。所以最好使用不同变量名,以免混淆。

    (3)函数的命名空间

    当一个函数被执行时,他产生了自己的命名空间。局部变量只能被指定函数访问--局部作用域,函数调用后,命名空间关闭。如果一个变量是局部赋值的,赋值前不能被引用。

    下例中,程序执行到第二个语句AddMoney()时,由于没有函数内money没有赋值,直接引用money=money+1,结果出错。

    money=200         #创建一个money变量,赋值200
    def AddMoney():   #创建一个AddMoney函数
    money=money+1 #创建一个表达式,money变量自加1
    
    print(money)      #输出money变量
    AddMoney()        #调用AddMoney函数
    200               #输出money变量为函数外变量,值为200
    #调用AddMoney函数时报错。函数内money没有赋值,直接引用money=money+1,结果出#错。   
    Traceback (most recent call last):
    
      File "<ipython-input-6-95d4a4095290>", line 6, in <module>
        AddMoney()
    
      File "<ipython-input-6-95d4a4095290>", line 3, in AddMoney
        money=money+1
    
    UnboundLocalError: local variable 'money' referenced before assignment
    

    (4)命名空间生命周期

    命名空间创建时期和生存周期都不一样. python编译器启动时,包含内置变量名的命名空间就创建了,并不会被删除。 对一个模块,当模块定义后,其全局命名空间也创建了。一般情况下编译器退出后模块命名空间就关闭了。

    https://study.163.com/provider/400000000398149/index.htm?share=2&shareId=400000000398149(博主视频教学主页)

     

  • 相关阅读:
    leetcode------Palindrome Number
    leetcode------Minimum Depth of Binary Tree
    leetcode------Binary Tree Level Order Traversal II
    leetcode------Plus One
    leetcode------Plus One
    leetcode------Min Stack
    leetcode------Binary Tree Level Order Traversal
    递归树与非递归树的不同实现【转载,个人感觉写的比较好的一篇,值得去思考】
    leetcode------Compare Version Numbers
    leetcode------Majority Element
  • 原文地址:https://www.cnblogs.com/webRobot/p/13045084.html
Copyright © 2011-2022 走看看