如何在python中强制属性为int?

2024-09-28 21:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下课程:

class C3DPoint(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    # Other methods

我想确定,如果有人设置v3dpoint.x = <sth>,它会抛出一个错误,以防vale不是字符串。你知道吗

如何做到这一点?你知道吗


Tags: 字符串selfobjectinitdef错误class课程
3条回答

你可以这样做:

variable_name: type = value

您可以在Python中键入函数参数,假设您使用的是当前版本,但目前不确定是哪个PEP实现了它。你知道吗

def __init__(x: int, y: int , z: int):

然而,这不会抛出打字错误,因为我们都是同意的成年人,因为你可以做一个类型检查。你知道吗

if not (isinstance x, int):
    # throw Error

好的Python设计避免了显式类型检查:“如果它像鸭子一样呱呱叫,那就是鸭子……”。因此,您应该首先尝试在类之外执行数据验证,或者根本不执行。你知道吗

说到这里,执行检查的一种方法是重新定义__setattr__as described here

class Point():

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def __setattr__(self, name, value):
        assert isinstance(value, str), "Value must be of type str"
        super().__setattr__(name, value)

p = Point('a', 'b', 'c')
p.x = 3

# AssertionError: Value must be of type str

相关问题 更多 >