python如何用变量给文件命名-Python中的模块引用和变量命名,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,这些变量用户可以自己定义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值