有什么方法可以获取所有可能的Python类变量,包括没有值的变量?
我正在创建一个类似于查询的类:
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之前,不是设置。
我无法找到一种动态检查所有可能的变量(设置)的方法,以检查是否保持不设置。理想情况下,我不想实现每次在此类中添加可能的查询维度时必须更改的验证
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
变量注释在班级身体执行过程中收集的 代码> __注释__ 您可以使用的属性。
这是在
通常,您不会直接访问此属性,而是使用 而不是提供一些便利。
The variable annotations collected during class body execution are stored in an
__annotations__
attribute which you can use.This is documented in the datamodel under the "Custom classes" section.
Usually, you would not access this attribute directly but use
inspect.get_annotations
instead, which provides a few conveniences.在 @Wim的解决方案上遵循,希望从
self
获得注释,以便validate
方法将与子类作用。以下是使用Inspect.get_annotations
的实现,但请注意它是一个3.10功能。Following on @wim's solution, it would be desirable to get annotations from
self
so that avalidate
method will work with subclasses. Following is an implementation usinginspect.get_annotations
- but note that its a 3.10 feature.我在想这样的事情
I was thinking of something like this