简体   繁体   English

在 Python 中的函数之间传递值的最佳实践

[英]best practice for passing values between functions in Python

What is pythonic best practice for allowing one function to use another function's returned values?允许一个 function 使用另一个函数的返回值的 pythonic 最佳实践是什么? eg Is it better to call one function within another, or better that function1 returns to the class, and class variables are assigned that are then used by function2?例如,在另一个中调用一个 function 是否更好,或者 function1 返回到 class 并分配 class 变量更好,然后由 function2 使用? Secondly, how many different ways could you pass values between functions?其次,您可以在函数之间传递多少种不同的值?

class adding:

    def get_values(self):
        x = input("input x")
        y = input("input y")
        z = input("input z")
        return x, y, z

    def use_values(self, x, y, z):
        print x+y+z

if name == 'main':
    dave = adding()
    x, y, z = dave.get_values()
    dave.use_values(x, y, z)

Or或者

    dave = adding()
    dave.use_values(*dave.get_values())

As import this would say, "explicit is better than implicit";正如import this所说,“显式优于隐式”; so go with the first form.所以 go 与第一种形式。

If the number of return values becomes large, let use_value take a sequence argument instead.如果返回值的数量变大,让use_value的是一个序列参数。

All ways are valid and depend completely on your subject domain and the compartmentalisation of functionality, the separation of concerns.所有方法都是有效的,并且完全取决于您的主题领域和功能的划分,关注点的分离。 In other words, it depends .换句话说,它取决于.

For example, you could have a class whose public API has 2 methods that both depend on a 3rd method, that you deem to be private.例如,您可能有一个 class,其公共 API 有 2 个方法,它们都依赖于您认为是私有的第三种方法。 It is your choice as a developer not to make that 3rd method part of the public API, yet it's there in your source code:作为开发人员,您可以选择不将第三种方法作为公共 API 的一部分,但它在您的源代码中:

class FooAPI(object):
    def publicMethodOne(*args, **kw):
        return self._privateMethod(1, *args, **kw) + 7

    def publicMethodTwo(*args, **kw):
        return self._privateMethod(2, *args, **kw) + 11

    def _privateMethod(somevalue, *args, **kw):
        return somevalue * 3

In that case, there is absolutely no need for users of your API to call _privateMethod directly and pass it's return value to either publicMethod .在这种情况下,您的 API 的用户绝对不需要直接调用_privateMethod并将其返回值传递给publicMethod

However, if you feel that consumers of your API should provide your method with specific information for which there is an easy default method that could calculate that specific information for them in most cases, you would want to pass in the return value of that default method.但是,如果您认为 API 的使用者应该为您的方法提供特定信息,在大多数情况下,有一个简单的默认方法可以为他们计算特定信息,您可能希望传入该默认方法的返回值. That way, those consumers can also use their own method of calculation and use those values instead :这样,这些消费者也可以使用他们自己的计算方法并使用这些值来代替

def publicMethod(value1, value2):
    return value1 / value2

def mostCommonValues():
    return (1.0, 4.0)

publicMethod(*mostCommonValues())
publicMethod(4, 2)

And when to use instance variables?以及何时使用实例变量? Only when the return values of a function are to persist with the instance, when they reflect the internal state of that instance.仅当 function 的返回值与实例保持一致时,当它们反映该实例的内部 state 时。

For example, if your class represents a car, it may make sense for your application to store the location of the car between operations on that car.例如,如果您的 class 代表一辆汽车,那么您的应用程序在对该汽车的操作之间存储汽车的位置可能是有意义的 So if you want to know if it needs to stop for a traffic light right now, call the updatePosition() method first, then use another method to calculate the distance from the traffic light.所以如果你想知道它现在是否需要停下来等红绿灯,首先调用updatePosition()方法,然后用另一个方法计算到红绿灯的距离。 You wouldn't pass the output of the updatePosition() call to the distance calculation method, you would just keep the position updated in the instance.您不会将updatePosition()调用的 output 传递给距离计算方法,您只需在实例中更新 position 即可。

If however, you need to update the position of the car in a collision, you'll need to take data from the car (based on return values from methods called on the car), combined with external information (position of other object, resistance of the road surface, etc.) to feed back into the updatePosition method on the car.但是,如果您需要在碰撞中更新汽车的 position,则需要从汽车获取数据(基于汽车上调用的方法的返回值),并结合外部信息(其他 object 的位置、电阻路面等)反馈到汽车上的updatePosition方法。 Because you now need to add additional information from outside the car instance, you'll have to pass in the values from one method call to the other via your public API.因为您现在需要从汽车实例外部添加其他信息,所以您必须通过公共 API 将值从一个方法调用传递到另一个方法调用。

Remember, software development is more an artform than a strict engineering discipline, and thus the answer as to how to do this varies from developer to developer and from software project to software project.请记住,软件开发与其说是严格的工程学科,不如说是一种艺术形式,因此如何做到这一点的答案因开发人员和软件项目而异。 There never is no one answer.从来没有一个答案。 Just try to make it explicit and obvious, natural.试着让它明确、明显、自然。

I would argue that get_values is not a vital part of adding and should thus be a separate function.我认为get_values不是添加的重要部分,因此应该是单独的 function。 If it should be I would say:如果应该是我会说:

class adding:

def get_values(self):
    self.x = input("input x")
    self.y = input("input y")
    self.z = input("input z")

def use_values(self):
    print self.x+self.y+self.z

if name == 'main':
    dave = adding()
    dave.get_values()
    dave.use_values()

is a more sound solution.是一个更合理的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM