程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Standard templates written by Python modules

編輯:Python

Python Standard template for module writing

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Module introduction 
' a test module '
# author 
__author__ = 'Michael Liao'
import sys
# Function definition 
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()

Python The interpreter takes a special variable __name__ Set as __main__, And if you import it elsewhere hello When the module ,if Judgment will fail , therefore , such if Testing allows a module to execute some extra code through the command line runtime , The most common is running tests .

Scope

In a module , We may define many functions and variables , But some functions and variables we want to use for others , Some functions and variables we want to use only inside the module . stay Python in , It's through _ Prefix to achieve .

Normal function and variable names are public (public), Can be quoted directly , such as :abc,x123,PI etc. ;

similar __xxx__ Such variables are special variables , Can be quoted directly , But there are special uses , Like the one above __author__,__name__ It's a special variable ,hello Module defined document annotations can also use special variables __doc__ visit , We don't use this variable name for our own variables ;

similar _xxx and __xxx Such functions or variables are not public (private), Should not be quoted directly , such as _abc,__abc etc. ;

The reason why we say ,private Functions and variables “ Should not be ” Be quoted directly , instead of “ You can't ” Be quoted directly , Because Python There is no way to completely restrict access private Function or variable , however , You should not refer to private Function or variable .

private Functions or variables should not be referenced , What's the use of them ? Please see the example :

def _private_1(name):
return 'Hello, %s' % name
def _private_2(name):
return 'Hi, %s' % name
def greeting(name):
if len(name) > 3:
return _private_1(name)
else:
return _private_2(name)

Using modules - Liao Xuefeng


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved