问题描述
我正在编写一个类,需要检查实例变量是否为某种类型。
I am writing a class where I need to check whether the instance variables are of a certain type.
我注意到有很多重复的代码。
是否有更好的方法对实例变量进行类似检查?
还是这是正确的方法?
I noticed that there is a lot of repeating code.Is there a better way to do similar checks on the instance variables?Or is this the right way to do it?
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')
推荐答案
这本书琼斯Beazley包含的食谱 9.21避免使用重复的属性方法几乎可以满足您的需要-我强烈建议您将本书(或电子书)的副本发送给有兴趣的人,以便他们尽快成为熟练的Python程序员包含许多这样的宝石。 (免责声明:我与发布者或作者没有任何隶属关系。)
The book Python Cookbook, 3rd Edition by Jones & Beazley contains recipe 9.21 Avoiding Repetitive Property Methods which does almost exactly what you need — I highly recommend getting a copy of the book (or e-book) to anyone interested becoming a proficient Python programmer more quickly as it contains many gems like this. (Disclaimer: I have no affiliation with the publisher or authors.)
Python中的所有内容都是一流的对象,因此可以简单地创建一个函数定义属性并返回它。通过这种方式,您可以遵循(并减少不必要的重复代码)。
Just about everything in Python is a first-class object, so it's possible to make a function that simply defines the property and returns it. Doing things this way will allow you to follow the DRY Principle (and write less boring redundant code).
def typed_property(name, expected_type):
storage_name = '__' + name
@property
def prop(self):
return getattr(self, storage_name)
@prop.setter
def prop(self, value):
if not isinstance(value, expected_type):
type_name = expected_type.__name__
raise TypeError('"{}" must be a {}'.format(name, type_name))
setattr(self, storage_name, value)
return prop
class Variable():
__type = 'Variable'
id = typed_property('id', int)
updateable = typed_property('updateable', bool)
name = typed_property('name', str)
value = typed_property('value', np.ndarray)
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
这篇关于为实例变量重复装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!