在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
您不能控制全局或局部变量的分配,但是可以覆盖类对象属性的分配。这是一个使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句