Python module reference and variable naming

#!/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__ Author information

Import the sys module

sysThe module has a argvvariable, all the parameters of the command line are stored in list. argvAt least one element, because the first parameter is always the name of the .py file

What you python3 hello.pyget from running sys.argvis ['hello.py'];

What you python3 hello.py Michaelget by running sys.argvis ['hello.py', 'Michael'].

When we run the module file on the command linehello , the Python interpreter sets a special variable __name__to __main__, and if the hellomodule is imported elsewhere , the ifjudgment will fail. This method is often used to test!

$ 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!

Variable definitions:

__xxx__ means special variables, for example __author__,__name__

_xxxAnd __xxxsuch functions or variables are non-public (private) and should not be directly quoted, for example _abc,__abc,这些变量用户可以自己定义。

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

 

Guess you like

Origin blog.csdn.net/li4692625/article/details/109499184