Skip to main content
 首页 » 编程设计

python之在类中包装一个函数

2025年05月04日15hnrainll

这并不是特定于语言的,但我将使用 Python 来解释我的问题。

我的程序有几个几乎独立的函数。命令行参数选择这些函数之一,并提供输入文件名。然后执行函数:

# main.py: 
import functions 
def main(): 
  filename = sys.argv[1] 
  function_name = sys.argv[2] 
  function = getattr(functions, function_name) 
  result = function(filename) 
  # do something with result 
 
# function.py contains all the functions: 
def function1(filename): 
  # ... 

我觉得我应该使用类而不是函数,所以我将每个函数都包装在一个类中。但是现在每个类看起来都非常愚蠢:它只被实例化一次,它所做的只是执行它的构造函数,这与我的旧函数所做的完全一样。然后我可以调用某个方法来检索返回值:

# new version of main.py: 
import classes 
def main(): 
  filename = sys.argv[1] 
  cls_name = sys.argv[2] 
  cls = getattr(classes, cls_name) 
  calculation = cls(filename) 
  result = calculation.result() 
  # do something with result 
 
# classes.py: 
import functions 
class Class1: 
  def __init__(self, filename): 
    self.result = functions.function1(filename) 
  def result(self): 
    return self.result 
 
# functions.py is unchanged 

这似乎并不比我有函数的时候好多少。有没有办法让我的代码以更有用的方式面向对象?

请您参考如下方法:

如果您正在编写 Java 或 C#,那么您会将这些函数实现为静态方法。在这些语言中,由于语言的设计,所有方法都必须是类的一部分。在 Python 中,虽然您可以模拟静态方法,但对于此示例完全没有必要这样做。

Python 的创造者 Guido van Rossum 拥有 argued in favour of the use of functions rather than methods .

First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:

(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation.

(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.

Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/

虽然这与您的问题没有直接关系,但它确实挑战了有时教条的立场,即方法总是优先于功能。

在我看来,在 Python 中,使用函数是比创建类更好的解决方案。