【发布时间】:2020-07-08 17:58:31
【问题描述】:
我正在编写一个类,我需要检查实例变量是否属于某种类型。
我注意到有很多重复的代码。 有没有更好的方法对实例变量进行类似检查? 或者这是正确的做法?
class Variable():
__type = 'Variable'
def __init__(self, id = None, updateable = True, name = 'Variable', value=None):
if id is not None:
self.id = id
if value is not None:
self.value = value
self.updateable = updateable
self.name = name
@property
def id(self):
return self.__id
@id.setter
def id(self, id=None):
if isinstance(id, int):
self.__id = id
else:
raise Exception('"id" must be an integer ')
@property
def updateable(self):
return self.__updateable
@updateable.setter
def updateable(self, updateable=None):
if isinstance(updateable, bool):
self.__updateable = updateable
else:
raise Exception('"updateatable" must be a bool')
@property
def name(self):
return self.__name
@name.setter
def name(self, name=None):
if isinstance(name, str):
self.__name = name
else:
raise Exception('"name" must be a string')
@property
def value(self):
return self.__value
@value.setter
def value(self, value=None):
if isinstance(value, np.ndarray):
self.__value = value
else:
raise Exception('"value" not an instance of np.ndarray')
【问题讨论】:
-
你看到这里的答案了吗? stackoverflow.com/questions/9305751/… 装饰器
auto_attr_check看起来很有趣,图书馆pydantic 可能会对您有所帮助。适合你吗? -
如果你使用python > 3.7,你可以查看dataclasses
标签: python class variables instance decorator