Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的独立部分_Python - Fatal编程技术网

Python中的独立部分

Python中的独立部分,python,Python,我想知道是否有一个最佳实践来分离Python中的代码块。例如,在MATLAB中,两个注释符号(%%)创建一个代码段。目前,我正在做: #### ## Import libraries #### import _mssql #Binary here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql #### ## Connect to db + Query the data #### q_file = open ("query.txt",

我想知道是否有一个最佳实践来分离Python中的代码块。例如,在MATLAB中,两个注释符号(
%%
)创建一个代码段。目前,我正在做:

####
## Import libraries
####

import _mssql #Binary here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql

####
## Connect to db + Query the data
####

q_file = open ("query.txt", "r")
query = q_file.read().replace('\n', '')

##Connect to the database
conn = _mssql.connect(server='', user='',
                      password='', database='')

##Query the database
conn.execute_query(query)
for row in conn:
    print(row)

####
## Data filtering
####

[...]

顶层使用模块,在各自的模块中实现单独的部分,然后参考主模块中的部分:

import random
import time

if time.time() > random.random():
    pass
下一级(可选,谨慎使用)使用类

class Foo:
    def function1():
        pass

class Bar:
    def function2():
        pass
下一级,您需要的是使用功能

def connect(...):
    filename = ...
    params = ...(filename)
    return mysql.connect(*params)

def mainloop(...):
    for xx in connect():
        pass
子级使用块

def foo(path=None, port=None):
    if not path:
        filename = ...
        path = ...(filename)

    if not port:
        foobar = ...
        port = ...(foobar)

    xxx.connect(path, port)
子层级使用空行和注释

def foo(...):
    bar.bar()

    assert path  # <-- this is essentially a comment
    smth_with(path)
    some_other()
    data = xxx.yyy()

    assert data
    foo = blahblah
    bar = lambda: blahblah
    filtered = filter(yada, data)

    # data is clean at this point  # <-- an actual comment
    for x, y in data:
        foo.bar.baz()
def foo(…):
bar.bar()

断言路径#Python很自然地提供了模块化结构,并为每一级结构提供了文档字符串

您的注释通常属于函数名或方法描述。然后代码自然读取。(有些注释非常明显,以至于毫无用处,例如“导入库”。)


请进一步参阅以指导您的文档工作。

您可以使用双引号<代码>“”
一般来说,我觉得当您需要将模块划分为不同的章节时,这意味着它太大了,不久前应该在不同的文件中进行分割。或者您的评论过多。Sypder IDE具有类似Matlab的代码单元()。为了构造我的代码,我尝试这样注释:当将sphinx()与numpydoc()一起使用时,我获得了一个有用的文档。这将导致注释具有自然的结构。您无法在文件、模块、类和函数级别显示文档字符串。这些对于任何代码可用性工作都是必不可少的。您是正确的,但遗漏是有意的。OQ涉及将代码分成块,我觉得docstring可能会产生误导,因为我认为每个模块、每个类、每个函数应该只有一个docstring;因此,文档字符串不能用于分隔两个代码块。
"""
Perform stuff.  Obviously this documentation should be more specific in reality.
"""

import _mssql  # Binary here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql


def run_query(filename):
    """
    Open connection to database, run the query in the file, and
    return rows as a list.
    """
    rows = []

    # Minor tweak: "with" takes care of closing the file when you're done
    with open (filename, "r") as q_file:
        query = q_file.read().replace('\n', '')

    conn = _mssql.connect(server='', user='',
                      password='', database='')

    conn.execute_query(query)
    for row in conn:
        # Maybe use yield here instead of reading all the results into memory
        rows.append(row)

    return rows

def filter_rows(rows):
    """
    Filter a list of rows: Remove any rows containing 'Albuquerque'.
    """
    # ....

results = filter_rows(run_query("query.txt"))