【发布时间】:2015-10-19 16:49:41
【问题描述】:
Python 作为一种动态语言,提供了多种方式来实现相同的功能。这些选项在可读性、可维护性和性能方面可能会有所不同。尽管我用 Python 编写的常用脚本是一次性的,但我现在有一个我正在从事的(学术)项目,该项目必须可读、可维护并且性能相当好。由于我之前没有在 Python 中进行过任何认真的编码,包括任何类型的分析,所以我需要帮助来决定我上面提到的三个因素之间的平衡。
这是我正在研究的科学包中的一个模块的代码 sn-p。它是一个具有非常基本骨架结构的 n 元树类。这是在考虑继承和子类的情况下编写的。
注意:在下面的代码中,树与节点相同。每棵树都是同一类树的一个实例。
class Tree(object):
def __init__(self, parent=None, value=None):
self.parent = parent
self.value = value
self.children = set()
以下两个函数属于这个类(以及许多其他函数)
def isexternal(self):
"""Return True if this is an external tree."""
return not bool(self.children)
def isleaf(self):
"""Return True if this is a leaf tree."""
return not bool(self.children)
这两个函数的作用完全相同——它们只是两个不同的名称。那么,为什么不将其更改为:
def isleaf(self):
"""Return True of this is a leaf tree."""
return self.isexternal()
我的疑惑是:
我读过 Python 中的函数调用相当昂贵(为每次调用创建新堆栈),但我不知道如果一个函数依赖于另一个函数是好事还是坏事。它将如何影响可维护性。这在我的代码中发生了很多次,我从另一种方法调用一个方法以避免代码重复。这样做是不好的做法吗?
这是同一类中这种代码重复场景的另一个示例:
def isancestor(self, tree):
"""Return True if this tree is an ancestor of the specified tree."""
return tree.parent is self or (not tree.isroot()
and self.isancestor(tree.parent))
def isdescendant(self, tree):
"""Return True if this tree is a descendant of the specified tree."""
return self.parent is tree or (not self.isroot()
and self.parent.isdescendant(tree))
我可以选择:
def isdescendant(self, tree):
"""Return True if this tree is a descendant of the specified tree."""
return tree.isancestor(self)
【问题讨论】:
标签: python performance optimization code-duplication