有什么方法可以缩短具有相似语句但不同 returns 的属性?
Is there any way I can shorten properties with similar statements but different returns?
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
所以当我调用 'hemisphere' 时它会 return 下摆值等等。
PS。
我知道我在后者的 return 语句是错误的。我希望你明白我的意思。
您可以覆盖 __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}'")
有很多方法可以缩短它,我会写另一个辅助函数:
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
)
正如@xjcl 评论的那样,在简单的基础上优先于看似不必要的 complication/obfuscation:
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]
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
所以当我调用 'hemisphere' 时它会 return 下摆值等等。
PS。 我知道我在后者的 return 语句是错误的。我希望你明白我的意思。
您可以覆盖 __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}'")
有很多方法可以缩短它,我会写另一个辅助函数:
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
)
正如@xjcl 评论的那样,在简单的基础上优先于看似不必要的 complication/obfuscation:
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]