Вопрос

I'm extracting features from a specific class of objects I have and decided to built a method that extracts all features at once, i.e. call all feature extraction methods and return them in a tuple, as shown below.

def extractFeatures(self):
    if self.getLength()<=10:
        return ()
    else:
        return (self.getMean(),     # a number
            self.getStd(),     # a number
            self.getSkew(),     # a number
            self.getKurt(),     # a number
            # Many other methods here, such as:
            self.getACF(), # which returns a TUPLE of numbers...
            )

Nevertheless, I have some methods returning tuples with numbers instead of individual numbers, and since I'm still doing some tests and varying the length in each one of these tuples, hard typing self.getACF()[0], self.getACF()[1], self.getACF()[2], ... is not a good idea.

Is there a pythonic way of getting these values already "unpacked" so that I can return a tuple of only numbers instead of numbers and maybe nested tuples of indefinite size?

Это было полезно?

Решение

You could build a list of the values to return, then convert to a tuple at the end. This lets you use append for single values and extend for tuples:

def extractFeatures(self):
    if self.getLength() > 10:
        out = [self.getMean(), self.getStd(), self.getSkew()]
        out.append(self.getKurt()] # single value
        out.extend(self.getACF()) # multiple values
        return tuple(out)

Note that this will implicitly return None if self.getLength() is 10 or less.

However, bear in mind that your calling function now needs to know exactly what numbers are coming and in what order. An alternative in this case is to return a dictionary:

return {'mean': self.getMean(), ... 'ACF': self.getACF()}

Now the calling function can easily access the features required by key, and you can pass these as keyword arguments to other functions with dictionary unpacking:

def func_uses_mean_and_std(mean=None, std=None, **kwargs):
    ...

features = instance.extractFeatures()
result = func_uses_mean_and_std(**features)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top