在 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
Run Code Online (Sandbox Code Playgroud)
您无法控制全局或局部变量的分配,但您可以覆盖类对象属性的分配。这是一个使用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
Run Code Online (Sandbox Code Playgroud)