我正在創建一個類來表示查詢,如下所示:
class Query:
height: int
weight: int
age: int
name: str
is_alive: bool = True
如您所見,一些變數開始時使用默認值進行初始化,而其他變數則沒有。
我想像這樣實作可鏈接的設定器
def of_height(self, height):
self.height = height
return self
def with_name(self, name):
self.name = name
return self
...
目標是從專案中的幾個地方呼叫它,如下所示:
q = Query()
q.of_height(175).with_name("Alice")
然后我想呼叫一個q.validate()檢查是否未設定任何欄位,然后再使用此查詢呼叫 API。
我想不出一種方法來動態檢查所有可能的變數,無論是否設定,以檢查是否有任何未設定。理想情況下,我不想實作validate每次在此類中添加可能的查詢維度時都必須更改的 a。
uj5u.com熱心網友回復:
在類主體執行期間收集的變數注釋存盤在__annotations__您可以使用的屬性中。
>>> Query.__annotations__
{'height': int, 'weight': int, 'age': int, 'name': str, 'is_alive': bool}
這記錄在“自定義類”部分下的資料模型中。
通常,您不會直接訪問此屬性,而是使用inspect.get_annotations它,這提供了一些便利。
uj5u.com熱心網友回復:
在@wim 的解決方案之后,最好從中獲取注釋,self以便validate方法可以與子類一起使用。以下是使用inspect.get_annotations- 但請注意它是 3.10 功能的實作。
#!/usr/bin/env python3.10
import inspect
import itertools
class Query:
height: int
weight: int
age: int
name: str
is_alive: bool = True
class Query2(Query):
foo: int
def get_annotated_attrs(self):
return set(itertools.chain.from_iterable(inspect.get_annotations(Q).keys() for Q in self.__class__.__mro__))
def validate(self):
for name in self.get_annotated_attrs():
if not hasattr(self, name):
return False
return True
q2 = Query2()
print(q2.get_annotated_attrs())
print(q2.validate())
uj5u.com熱心網友回復:
我在想這樣的事情
import inspect
class Query:
height: int
weight: int
age: int
name: str
is_alive: bool = True
avilable_dimentions = ['height', 'weight', 'age', 'name', 'is_alive']
def of_height(self, height):
self.height = height
return self
def with_name(self, name):
self.name = name
return self
def validate(self):
not_defined = []
for dim in self.avilable_dimentions:
try:
eval(f'self.{dim}')
except:
not_defined.append(dim)
if not_defined:
raise Exception(f'Missing dimentions {not_defined}')
return self
class Query2(Query):
height2: int
weight2: int
avilable_dimentions = Query.avilable_dimentions ['height2', 'weight2']
q = Query2()
q = q.of_height(175).with_name("Alice").validate()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487432.html
上一篇:yum安裝 一直出現There are no enabled repositories in “/etc/yum.repos.d“, “/etc/yum/repos.d“, 的解決辦法
