博客
关于我
python 模块和包,系统模块,时间模块,哈希摘要(3.17)
阅读量:509 次
发布时间:2019-03-07

本文共 4584 字,大约阅读时间需要 15 分钟。

A Job Interview Question (Output Judgment)

Question Analysis

The code snippet provided has a list list1 where an anonymous function is dynamically added for each iteration. The function definition is stored in the list rather than being immediately called. After the loop completes, the functions are called with x=2 to produce specific outputs. The challenge is to determine the expected result based on the closure behavior in Python.

Solving the Problem

The list1 is populated with anonymous functions that capture the i variable from their enclosing scope. Even though the functions are defined inside a loop, their references to i are late-bound. This means that after the loop completes and i is finally set to 4, all functions in the list will refer to this same value of i when they are called. Thus, the output of each function call will be 4 * 2 = 8.

Step-by-Step Explanation

  • The loop runs from i = 0 to i = 4.
  • Each iteration creates an anonymous function that captures the current value of i.
  • The functions are stored in list1 but are not immediately called.
  • When print(list1[0](2)) is called, i has been set to 4, so the returned function calls 4 * 2 = 8.
  • Similarly, print(list1[2](2)) and print(list1[4](2)) also yield 8 because all closures reference the final value of i at the time the loop completes.
  • Module and Package

    Module Basics

    • A .py file represents a module. The file name is its module name.
    • The module name must be a valid identifier and not a reserved keyword to be usable by other modules.

    Package Concepts

    • A package is a file folder containing an __init__.py file. This special file signals Python that the folder is a package.

    Importing Modules

    There are several ways to import modules:

  • Basic Import:

    import module_name
    • Imports the entire module and allows access to its attributes using module_name.attribute.
  • Implicit Import:

    from module_name import variable1, variable2
    • Imports specific variables from the module and uses them without the module name prefix.
  • Alias Import:

    import module_name as new_module_name
    • Gives the imported module a new name for convenience.
  • Star Import:

    from module_name import *
    • Imports all global variables from the module.
  • Module Import Principles

    • The import statement examines the module and executes its code if required, depending on whether the module has been imported before.
    • The if __name__ == '__main__': guard clause prevents the module's main code from executing when the module is imported.

    Importing Packages

    To import a package or a module within a package:

  • Importing a Package:

    import package_name
    • This imports the entire package, making its contents accessible through package_name.module_name.
  • Importing a Specific Module:

    from package_name.module_name import *
    • This imports all exports from the specified module within the package.
  • __init__.py File Purpose

    The __init__.py file runs automatically when Python imports the package. It initializes the package and can define constants, default values, or functions related to the package.

    System Modules

    Entertaining Modules

    • turtle: For creating graphics in Python.

      import turtleturtle.polygon(3)  # Draw a triangle
    • smtplib: For sending email.

      import smtplibsmtp = smtplib.SMTP('smtp.example.com')smtp.sendmail(from_addr, to_addr, message)

    Commonly Used System Modules

    1. os Module

    Reverse Example:

    import os# List current working directoryos.getcwd() # List directory contentsos.listdir('path_to_folder')

    2. time and datetime Modules

    • time(): Returns the current timestamp in seconds.
      import timet1 = time.time()print(t1)  # ~4-byte timestamp
    • datetime: Combines date and time into a single object.
      from datetime import datetime, timedeltanow = datetime.now()print(now)  # 'YYYY-MM-DD HH:MM:SS'
    • Time Manipulation:
      future = now + timedelta(days=10)print('10 days later:', future)

    3. random Module

    • Generate random numbers:

      import random# Random between 10 and 20print(random.randint(10, 20))# Random float between 0 and 1print(random.random())
    • Shuffle a list:

      nums = [23, 34, 'abc', True]random.shuffle(nums)print(nums)
    • هاش ازlied from a sequence:

      import randomresult = random.choice('abc3lo901')print(result)nums = [23, 34, 'abc', 20, 3, 4]result = random.choices(nums, k=2)print(result)

    4. hashlib Module

    • Compute hashes:
      import hashlibhash_obj = hashlib.md5()hash_obj.update(b'123456')print(hash_obj.hexdigest())

    Conclusion

    This was an overview of various Python concepts, including functions, modules, packages, and commonly used system libraries. The content covers essential tools every Python programmer should be familiar with when developing applications.

    转载地址:http://frrjz.baihongyu.com/

    你可能感兴趣的文章
    Objective-C实现最长子数组算法(附完整源码)
    查看>>
    Objective-C实现最长字符串链(附完整源码)
    查看>>
    Objective-C实现最长递增子序列算法(附完整源码)
    查看>>
    Objective-C实现有限状态机(附完整源码)
    查看>>
    Objective-C实现有限状态自动机FSM(附完整源码)
    查看>>
    Objective-C实现有限集上给定关系的自反关系矩阵和对称闭包关系矩阵(附完整源码)
    查看>>
    Objective-C实现朴素贝叶斯算法(附完整源码)
    查看>>
    Objective-C实现杰卡德距离算法(附完整源码)
    查看>>
    Objective-C实现极值距离算法(附完整源码)
    查看>>
    Objective-C实现构造n以内的素数表(附完整源码)
    查看>>
    Objective-C实现某文件夹下文件重命名(附完整源码)
    查看>>
    Objective-C实现查找整数数组中给定的最小数字算法(附完整源码)
    查看>>
    Objective-C实现根据cpu和磁盘序列号生成注册码( 附完整源码)
    查看>>
    Objective-C实现格雷码序列算法(附完整源码)
    查看>>
    Objective-C实现桥接模式(附完整源码)
    查看>>
    Objective-C实现检查给定图中是否存在循环算法(附完整源码)
    查看>>
    Objective-C实现检查给定字符串是否在camelCase中算法(附完整源码)
    查看>>
    Objective-C实现欧几里得距离(附完整源码)
    查看>>
    Objective-C实现求a的逆元x(附完整源码)
    查看>>
    Objective-C实现求众数(附完整源码)
    查看>>