初学者想知道他的代码是否“符合Python风格”

23 投票
12 回答
2581 浏览
提问于 2025-04-11 09:26

这是我第一次用Python写代码。我之前是用Java的。我不想只是用Python的语法来写Java代码,我想学习如何用Python的方式来编程。

你们能帮我看看怎么能让下面的代码更符合Python的风格吗?

from math import sqrt

# recursively computes the factors of a number
def factors(num):
    factorList = []
    numroot = int(sqrt(num)) + 1
    numleft = num
    # brute force divide the number until you find a factor
    for i in range(2, numroot):
        if num % i == 0:
            # if we found a factor, add it to the list and compute the remainder
            factorList.append(i)
            numleft = num / i
            break
    # if we didn't find a factor, get out of here!
    if numleft == num: 
        factorList.append(num)
        return factorList
    # now recursively find the rest of the factors
    restFactors = factors(numleft)
    factorList.extend(restFactors)

    return factorList

# grabs  all of the twos in the list and puts them into 2 ^ x form
def transformFactorList(factorList):
    num2s = 0
    # remove all twos, counting them as we go
    while 2 in factorList:
        factorList.remove(2)
        num2s += 1
    # simply return the list with the 2's back in the right spot
    if num2s == 0: return factorList
    if num2s == 1:
        factorList.insert(0, 2)
        return factorList
    factorList.insert(0, '2 ^ ' + str(num2s))
    return factorList

print transformFactorList(factors(#some number))

12 个回答

17

还有一件事你可能想看看,那就是文档字符串。比如,这个函数的注释:

# recursively computes the factors of a number
def factors(num):

可以改成这样:

def factors(num):
    """ recursively computes the factors of a number"""

虽然这样做并不是绝对必要的,但养成这个习惯是个好主意,特别是当你开始使用像pydoc这样的工具时。

你还可以这样做:

docstring.py

"""This is a docstring"""

在命令行中:

>>> import docstring
>>> help(docstring)

结果:

Help on module docstring:

NAME
    docstring - This is a docstring

FILE
    /Users/jason/docstring.py
21

只需要用'import math'和'math.sqrt()',而不是'from math import sqrt'和'sqrt()'。直接导入'sqrt'并没有什么好处,而且如果用太多的from-import,代码会变得很难管理。另外,像reload()和测试时的mocking这些东西,使用太多from-import会让它们更容易出问题。

divmod()函数是一个很方便的工具,可以同时进行除法和取余。你可以用for/else来代替对numleft的单独检查。你的factors函数很适合用生成器来写。xrange()在其他回答中已经提到过。下面就是这样写的:

import math

# recursively computes the factors of a number as a generator
def factors(num):
    numroot = int(math.sqrt(num)) + 1
    # brute force divide the number until you find a factor
    for i in xrange(2, numroot):
        divider, remainder = divmod(num, i)
        if not remainder:
            # if we found a factor, add it to the list and compute the
            # remainder
            yield i
            break
    else:
    # if we didn't find a factor, get out of here!
        yield num
        return
    # now recursively find the rest of the factors
    for factor in factors(divider):
        yield factor

使用生成器意味着你只能遍历结果一次;如果你只是想要一个列表(就像在translateFactorsList中那样),你需要把对factors()的调用放在list()里面。

22

有一本很棒的入门书,叫做《像Pythonista一样编写代码》,作者是David Goodger,可以在这里找到。书中有一些关于命名的建议(引用如下):

  • 函数、方法和属性用joined_lower这种风格命名

  • 常量可以用joined_lower或者全大写ALL_CAPS来命名

  • 类的命名用StudlyCaps风格

  • 只有在需要遵循已有的命名规则时,才使用camelCase风格

撰写回答