我之前的属性获取器/设置器
class Child(Base):
@property
def prop(self) -> Optional[int]:
"""Doc"""
return getattr(self, "_prop", None)
@prop.setter
def prop(self, value: int):
self._set("prop", value) # where _set itself is a method to reduce boilerplate
现在,
prop = Prop.int_prop("prop", "Doc")
Prop.int_prop看起来像这样:
@staticmethod
def int_prop(name: str, doc: str) -> property:
def fget(self: Base) -> Optional[int]:
return getattr(self, "_" + name, None)
def fset(self: Base, value: int) -> None:
self._set(name, value)
return property(fget, fset, doc=doc)
编辑:_set方法
# Dump value to event store if event exists
event = self._events.get(name)
if event:
logger.info(f"Dumping value {value} to {repr(event)}")
event.dump(value)
# Assign value to local variable
setattr(self, "_" + name, value)
一方面,这让我感到自豪,因为我正在从事的项目中有近 70% 是属性 getter/setter。虽然我同意上面的方法更加 Pythonic 和干净,但下面的方法减少了很多代码。但是,它剥夺了 VS Code 在属性名称下方显示文档字符串的能力。
有没有解决这个问题或一般更好的方法?