python 中的小技巧

1 __name__

在 python 中, 所有的内容都是对象. 脚本本身也可以被当作模板 (modules) 对象, 而模板对象有一个内置属性 __name__. 这个属性的赋值依赖于用户怎么使用它: 如果直接运行它, 比如脚本文件 wordCount.py, 则 __name__ 属性就等于 __main__; 如果把它当作库, 在其他程序使用 import wordCount 时, __name__ 属性就等于 wordCount. 因此, 大家常常使用这个技巧来做简单的测试, 或者把它作为程序的主入口.

1.1 示例

# -*- coding: UTF-8 -*-
"""
此脚本用于展示如何用 Python 实现 word count
"""


# 保证脚本与Python3兼容
from __future__ import print_function


def wordCount(data):
    """
    输入一个字符串列表,统计列表中字符出现的次数

    参数
    ----
    data : list[str], 需要统计的字符串列表

    返回
    ----
    re : dict, 结果hash表,key为字符串,value为对应的出现次数
    """
    re = {}
    for i in data:
        re[i] = re.get(i, 0) + 1
    return re


if __name__ == "__main__":
    data = ["ab", "cd", "ab", "d", "d"]
    print("The result is %s" % wordCount(data))
    # The result is {'ab': 2, 'd': 2, 'cd': 1}

2 使用 type 函数得到调用对象的类型

3 使用 dir 函数得到调用对象的所有属性和方法

4 Python 中的每个对象 (类和函数) 都有一个默认的 __doc__ 变量, 其记录了对象的使用说明

你可能感兴趣的:(python 中的小技巧)