我之前的屬性 getter/setter
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 在屬性名稱下方顯示檔案字串的能力。
是否有解決此問題的解決方案或一般更好的方法?
uj5u.com熱心網友回復:
除非 VS Code 支持 PEP-257 對屬性檔案字串的定義,否則這只能被視為擴展注釋而不是正確答案。我從未使用過 VS Code,也無法測驗它對此的支持。
在其防御中,它在語法上提供檔案字串,而不是__doc__在運行時動態設定屬性,因此它有可能解決問題中提出的主要問題。
如果我不關心 IDE 支持,我會撰寫一個自定義描述符并遵循PEP-257屬性檔案字串指南。
# Adapted from examples in https://docs.python.org/3/howto/descriptor.html
class IntPropety:
def __set_name__(self, owner, name):
self.public_name = name
self.private_name = "_" name
def __get__(self, obj, objtype=None) -> Optional[int]:
if obj is None:
return self
return getattr(obj, self.private_name)
def __set__(self, obj, value):
event = obj._events.get(self.public_name)
if event:
logger.info(f"Dumping value {value} to {repr(event)}")
event.dump(value)
setattr(obj, self.private_name, value)
class Child(Base):
prop = IntProperty()
"""Doc"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323892.html
下一篇:從C 中的其他子類呼叫函式
