1

Imagine I have the following two methods:

 def function(self, my_object):
     self.things.add(my_object)

 def function_args(self, arg1, arg2, arg3 = None):
     my_object = MyObject(arg1, arg2, arg3)
     self.things.add(my_object)

I would like to write this as a single function that can be called with positional parameters:

 something.function(an_object)
 something.function(arg1, arg2, arg3)

I can see how to do it if I'm willing to always call the resulting function with keyword arguments, and I can see how to do it if I'm willing to change the signature of the second function to accept a list or tuple of the three arguments, so that each version has single argument and I can differentiate by type (which doesn't seem quite right in Python).

Can I cleanly write a single function that will allow me to call it with either set of positional arguments?

4

4 回答 4

1

为什么不将 arg2 设置为可选并在调用函数时检查它?

 def function_args(self, arg1, arg2 = None, arg3 = None):
     if arg2 != None:
       my_object = MyObject(arg1, arg2, arg3)
       self.things.add(my_object)
     else:
       self.things.add(arg1)
于 2012-05-11T16:51:56.790 回答
1

我不会把这个想法称为非常pythonic,但这样的事情会起作用:

def fun(*args):
    obj = args[0]
    if not isinstance(obj, MyClass):
        obj = MyClass(*args)

我们不知道您的 API 是什么,但由于您在评论中提到了对象重用,也许您可​​以使其对最终用户透明,例如:

def fun(arg1, arg2, arg3=None):
    key = arg1 + arg2 + arg3
    if key not in cache:
        cache[key] = MyClass(arg1, arg2, arg3)
    obj = cache[key]
    ...
于 2012-05-11T16:58:59.370 回答
0
def function(self, *args, my_object=None)
    if my_object is None:
        my_object =  MyObject(*args)
    self.things.add(my_object)

这要求您将 my_object 作为关键字参数传递,但 IMO 这正是您想要的,因为它暗示了所涉及的魔法。

如果您真的不想要关键字参数,请将其删除,然后检查 len(args) 是否有分支。

于 2012-05-11T16:52:21.463 回答
0

我可以干净地编写一个允许我使用任意一组位置参数调用它的函数吗?

我不这么认为。但这是另一个接近接近的尝试。

def fn(self, a, *args):
    if args:
        self.things.add(MyObject(*((a,) + args)))
    else:
        self.things.add(a)
于 2012-05-11T17:32:21.910 回答