python的模块引用和变量命名

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

' a test module '

__author__ = 'Michael Liao'

import sys

def test():
    args = sys.argv
    if len(args)==1:
        print('Hello, world!')
    elif len(args)==2:
        print('Hello, %s!' % args[1])
    else:
        print('Too many arguments!')

if __name__=='__main__':
    test()

__author__ 作者信息

导入sys模块

sys模块有一个argv变量,用list存储了命令行的所有参数。argv至少有一个元素,因为第一个参数永远是该.py文件的名称

运行python3 hello.py获得的sys.argv就是['hello.py']

运行python3 hello.py Michael获得的sys.argv就是['hello.py', 'Michael']

当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,这种方法常用来测试!

$ python3 hello.py
Hello, world!
$ python hello.py Michael
Hello, Michael!

$ python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
#直接调用方法才会运行test
>>> hello.test()
Hello, world!

变量定义:

__xxx__表示特殊变量,比如__author____name__

_xxx__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc__abc,这些变量用户可以自己定义。

参考来源:https://www.liaoxuefeng.com/wiki/1016959663602400/1017455068170048

猜你喜欢

转载自blog.csdn.net/li4692625/article/details/109499184