首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >验证Python类的条件属性

验证Python类的条件属性
EN

Stack Overflow用户
提问于 2022-05-16 20:07:07
回答 1查看 41关注 0票数 0

我有一个有几个属性的类。我可以使用@property装饰器来验证每个属性。但是,我也想验证条件属性。现在,我正在使用在init方法中调用的验证函数。有更好的办法吗?

我现在就是这样做的。

代码语言:javascript
运行
复制
class Foo:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.validate()
   
    def validate(self):
        if self.x > 100 and self.y > 100:
           raise ValueError("Object outside of bounds!")
        elif isintance(self.y, int) and not isintance(self.x, int):
           raise ValueError("Mismatched types!")
        elif...
EN

回答 1

Stack Overflow用户

发布于 2022-05-16 20:25:29

我将在__init__中直接使用助手函数进行验证。

代码语言:javascript
运行
复制
class Foo:
    def __init__(self, x, y):
        if x > 100 and y > 100:
            raise ValueError("x and y cannot both be greather than 100")
        if not (isinstance(x, type(y)) and isinstance(y, type(x))):
            raise ValueError("x and y have different types")
        self.x = x
        self.y = y


class Bar:
    def __init__(self, x, y):
        self.validate(x, y)
        self.x = x
        self.y = y

    @staticmethod
    def validate(x, y) -> bool:
        if x > 100 and y > 100:
            raise ValueError("x and y cannot both be greather than 100")
        if not (isinstance(x, type(y)) and isinstance(y, type(x))):
            raise ValueError("x and y have different types")
        return True
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72265008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档