用一个函数写不同的class属性
Use a function to write different class attributes
我想创建一个函数来写入 Python class 中的属性,但能够决定是否应该写入该属性。
class Test(object):
def __init__(self):
self.a = None
self.b = None
def write_attrib(self,which_attrib,value):
# perform a check here
which_attrib = value
def write_a(self,value):
self.write_attrib(self.a, value)
def write_b(self,value):
self.write_attrib(self.b, value)
if __name__ == '__main__':
t = Test()
t.write_a(5)
t.write_b(4)
print(t.a, t.b)
现在这将导致两个值都为 None
,因此函数未触及它们。
我想采用这种方法,这样我就可以在编写属性之前在 write_attrib
中进行一些检查,而且我不必将这些检查写两次(但我想使便利功能 write_a
和 write_b
可用)。
使用property
class Test(object):
def __init__(self):
self._a = None
@property:
def a(self):
return self._a
@a.setter
def a(self, value):
# Do your validation here
self._a = value
根据我的评论,您可以实现 __setattr__
以仅验证您指定的属性:
class Test(object):
VALIDATED = {'a', 'b'}
def __init__(self):
self.a = None
self.b = None
def __setattr__(self, attr, val):
if attr in self.VALIDATED:
pass # add your checking
super(Test, self).__setattr__(attr, val)
或者,您可以为要验证的属性实施 @property
,管理对 private-by-convention 属性的访问(在标识符):
class Test(object):
def __init__(self):
self.a = None
self.b = None
@property
def a(self):
return self._a
@a.setter
def a(self, val):
# add your checking here
self._a = val
@property
def b(self):
return self._b
@b.setter
def b(self, val):
# add your checking here
self._b = val
如果您有许多具有相同验证规则的属性,则前者可能更简洁,如果您的属性较少,则后者可能 and/or 每个属性都有不同的验证规则。两者都允许您拥有干净的属性访问权限,无需 getter 或 setter(参见 Python @property versus getters and setters)。
我想创建一个函数来写入 Python class 中的属性,但能够决定是否应该写入该属性。
class Test(object):
def __init__(self):
self.a = None
self.b = None
def write_attrib(self,which_attrib,value):
# perform a check here
which_attrib = value
def write_a(self,value):
self.write_attrib(self.a, value)
def write_b(self,value):
self.write_attrib(self.b, value)
if __name__ == '__main__':
t = Test()
t.write_a(5)
t.write_b(4)
print(t.a, t.b)
现在这将导致两个值都为 None
,因此函数未触及它们。
我想采用这种方法,这样我就可以在编写属性之前在 write_attrib
中进行一些检查,而且我不必将这些检查写两次(但我想使便利功能 write_a
和 write_b
可用)。
使用property
class Test(object):
def __init__(self):
self._a = None
@property:
def a(self):
return self._a
@a.setter
def a(self, value):
# Do your validation here
self._a = value
根据我的评论,您可以实现 __setattr__
以仅验证您指定的属性:
class Test(object):
VALIDATED = {'a', 'b'}
def __init__(self):
self.a = None
self.b = None
def __setattr__(self, attr, val):
if attr in self.VALIDATED:
pass # add your checking
super(Test, self).__setattr__(attr, val)
或者,您可以为要验证的属性实施 @property
,管理对 private-by-convention 属性的访问(在标识符):
class Test(object):
def __init__(self):
self.a = None
self.b = None
@property
def a(self):
return self._a
@a.setter
def a(self, val):
# add your checking here
self._a = val
@property
def b(self):
return self._b
@b.setter
def b(self, val):
# add your checking here
self._b = val
如果您有许多具有相同验证规则的属性,则前者可能更简洁,如果您的属性较少,则后者可能 and/or 每个属性都有不同的验证规则。两者都允许您拥有干净的属性访问权限,无需 getter 或 setter(参见 Python @property versus getters and setters)。