0
class....

    @property
    def degrees(self):
        hem, degs, mins, secs = self._correction()
        return degs

    @property
    def minutes(self):
        hem, degs, mins, secs = self._correction()
        return mins

    @property
    def seconds(self):
        hem, degs, mins, secs = self._correction()
        return secs

我在想def可以被截断为:

@property
def hemisphere, degrees, minutes, seconds(self):
    hem, degs, mins, secs = self._correction()
    return hem, degs, mins, secs

这样当我调用“半球”时,它会返回下摆值等等。

PS。我知道我在后者中的return声明是错误的。我希望你明白我的意思。

4

3 回答 3

0

你可以覆盖__getattr__方法

def __getattr__(self, item):
    values = ["hemisphere", "degrees", "minutes", "seconds"]
    if item in values:
        return self._correction()[values.index(item)]
    raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{item}'")
于 2020-07-12T14:09:30.097 回答
0

有很多方法可以缩短它,我会编写另一个辅助函数:

from functools import wraps

def unpack(rng, fn, propertize=False):
    for i in rng:
        @wraps(fn)
        def wrapper(*args, __i=i, **kwargs):
            return fn(*args, **kwargs)[i]
        yield property(wrapper) if propertize else wrapper

...

class Something:
    hemisphere, degrees, minutes, seconds = unpack(
        range(4), Something._correction, propertize=True
    )
于 2020-07-12T14:10:57.300 回答
0

正如@xjcl 评论的那样,并且基于简单性而不是看似不必要的复杂化/混淆:

class....

    @property
    def degrees(self):
        return self._correction()[1]

    @property
    def minutes(self):
        return self._correction()[2]

    @property
    def seconds(self):
        return self._correction()[3]
于 2020-07-15T10:57:38.377 回答