这不会在编译时给你检查,但正如你建议使用 try/catch,我会假设运行时检查也会有帮助。
如果你使用类,你可以在__setattr__
方法中挂上你自己的类型检查。例如:
import datetime
# ------------------------------------------------------------------------------
# TypedObject
# ------------------------------------------------------------------------------
class TypedObject(object):
attr_types = {'id' : int,
'start_time' : datetime.time,
'duration' : float}
__slots__ = attr_types.keys()
# --------------------------------------------------------------------------
# __setattr__
# --------------------------------------------------------------------------
def __setattr__(self, name, value):
if name not in self.__slots__:
raise AttributeError(
"'%s' object has no attribute '%s'"
% (self.__class__.__name__, name))
if type(value) is not self.attr_types[name]:
raise TypeError(
"'%s' object attribute '%s' must be of type '%s'"
% (self.__class__.__name__, name,
self.attr_types[name].__name__))
# call __setattr__ on parent class
super(MyTypedObject, self).__setattr__(name, value)
这将导致:
>>> my_typed_object = TypedObject()
>>> my_typed_object.id = "XYZ" # ERROR
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 28, in __setattr__
TypeError: 'MyTypedObject' object attribute 'id' must be of type 'int'
>>> my_typed_object.id = 123 # OK
您可以继续使TypedObject
上述内容更通用,以便您的类可以继承它。
另一个(可能更好的)解决方案(在此处指出)可能是使用Entought Traits