How to pass variables in and out of functions in Python

This question already has an answer here:

  • How do you return multiple values in Python? 13 answers

  • 你可以利用kwargs来解压命名变量

    def foo(**kwargs):
        kwargs['var1'] = do_something(kwargs['var1'])
        ...
        return kwargs
    

    If you find yourself writing a lot of functions that act on the same data, one better way would be using classes to contain your data.

    class Thing:
        def __init__(self, a, b, c):
            var_1 = a
            var_2 = b
            var_3 = c
    
        # you can then define methods on it
    
        def foo(self):
            self.var_1 *= self.var_2
    
    # and use it
    t = Thing(1, 2, 3)
    t.foo()
    print(t.var_1)
    

    There are a number of methods of creating these in an easier way. Some of them include:

    attrs:

    >>> @attr.s
    ... class SomeClass(object):
    ...     a_number = attr.ib(default=42)
    ...     list_of_numbers = attr.ib(default=attr.Factory(list))
    ...
    ...     def hard_math(self, another_number):
    ...         return self.a_number + sum(self.list_of_numbers) * another_number
    

    namedtuples

    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
    >>> p.x + p.y               # fields accessible by name
    33
    

    Dataclasses

    These are not in python yet, but will be added in 3.7. I am adding them in here here because they will likely be the tool of choice in the future.

    链接地址: http://www.djcxy.com/p/53128.html

    上一篇: 在这段代码中我应该改变什么来返回两个列表?

    下一篇: 如何在Python中传入和传出函数中的变量