在Python中声明变量的严格数据类型?

时间:2016-02-09 20:04:22

标签: python

在python中,是否有一个命令(或指令)在为变量赋值不同于先前分配的类型时会发出警告?

x = int()   # "x" declared as integer
y = float() # "y" declared as float
x = 5       # "x" assigned an integer
y = 2.75    # "y" assigned a float
print(x)    # prints "5"
print(y)    # prints "2.75"
x = y       # !!! "x" is assigned a float; no warning raised !!!
print(x)    # prints 2.75

2 个答案:

答案 0 :(得分:2)

您无法控制全局变量或局部变量的赋值,但您可以覆盖类对象属性的赋值。这是一个使用 setattr 来强制执行类型的类。它有一个分配静态类型的方法(例如,使用int而不是int()),也可以在第一次赋值时指定类型。它对类型非常严格,但可以更改为允许继承类型。

class BabySitter(object):

    def __init__(self):
        object.__setattr__(self, "_types", {})

    # if you want static assignment
    def set_type(self, name, _type):
        self._types[name] = _type

    def __setattr__(self, name, value):
        _type = self._types.get(name)
        if _type:
            if type(value) is not _type: # or `if not isinstance(value, _type)`
                raise ValueError(
                    "BabySitter type conflict assigning '{}': was {} is {}".format(
                    name, _type, type(value)))
        # if you want dynamic assignment
        else:
            self._types[name] = type(value)
        object.__setattr__(self, name, value)

var = BabySitter()
var.set_type("x", int)     # static "x" declared as integer
var.set_type("y", float)   # static "y" declared as float
var.z = 123     # dynamic "z" int because of first assignment
var.x = 5       # "x" assigned an integer
var.y = 2.75    # "y" assigned a float
print(var.x)        # prints "5"
print(var.y)        # prints "2.75"
var.x = var.y           # <== exception is raised
print(var.x)        # prints 2.75

答案 1 :(得分:2)

Python 3.6版和更高版本支持类型检查。查看这篇文章:
How to Use Static Type Checking in Python 3.6
它是由Adam GeitGey撰写的-早在2017年。无需使用其他语言!