문제

I'm trying to make convenient passing some set of arguments to a number of functions (say 20).

Consider the following MWE (of course I don't really consider doing additions in such way):

def function(a, b):
    return a + b


class summation:
    def __init__(self, a, b):
        self.a = a
        self.b = b


s = summation(1,2)

function(**s.__dict__)

The reason I'm trying to do it is I have a bunch of functions all receiving 4 same arguments and I need to process them in a pipeline, passing from one function to another.

Implying that s always has only relevant fields is it a good way to pass arguments?

도움이 되었습니까?

해결책

It's a bad idea in general to use obj.__dict__ because the object dictionary does not contain any descriptors or other "magic" attributes that may exist on the object. It will also include hidden attributes that, by convention, are hidden behind a _ prefix. Thus, the obj.__dict__ technique really only works for completely basic types, and is not future proof if you decide to update any attributes to be properties so that you can control their getters/setters, etc. vars(obj) has this same issue.

class Rectangle(object):
    x = 0
    y = 0
    _width = 0
    height = 0

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        if value < 0:
            value = -value
            self.x -= value
        self._width = value

>>> r = Rectangle()
>>> r.__dict__
{}
>>> # this is because everything is class-level properties so far
>>> r.width = 50
>>> r.__dict__
{'_width': 50}

다른 팁

Namedtuple does this for you outright.

Here's a talk from PyCon US 2011 [11:35 - 26:00]

from collections import namedtuple
Add = namedtuple("Add", "a b c d")

one = Add(1, 2, 3, 4)

def addme(a, b, c, d):
    print a + b
    print c + d

>>> addme(*one)
... 3
... 7
for attribute, attribute_value in obj.__dict__.items():  # or obj.__dict__.iteritems() 
    print attribute, attribute_value
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top