发布了一个非常相似的问题here,但没有公认的答案,没有代码示例,而且我不太喜欢按照那里提供的唯一一个答案所建议的使用外部库的想法。
以下代码允许定义只读实例属性:
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
return self._y
但我也想验证用户输入。我想验证是否x
and y
有正确的类型。
最Pythonic/优雅的方法是什么?如果我提供设置器,属性就不再是只读的。
在构造函数中执行输入验证是唯一的方法吗?
这是一种优雅且Python式的方法,它使用工厂函数来创建属性:
class ReadOnlyError(Exception):
"""Attempt made to assign a new value to something that can't be changed."""
# Based on recipe in book "Python Cookbook 3rd Edition" - section 9.21 -
# titled "Avoiding Repetitive Property Methods".
def readonly_typed_property(name, expected_type):
storage_name = '_' + name
@property
def prop(self):
return getattr(self, storage_name)
@prop.setter
def prop(self, value):
if hasattr(self, storage_name):
raise ReadOnlyError('{!r} is read-only!'.format(name))
if not isinstance(value, expected_type):
raise TypeError('{!r} must be a {!r}'.format(name, expected_type.__name__))
setattr(self, storage_name, value)
return prop
class Point:
x = readonly_typed_property('x', int)
y = readonly_typed_property('y', int)
def __init__(self, x, y):
self.x = x
self.y = y
if __name__ == '__main__':
try:
p1 = Point(1, 2)
except Exception as e:
print('ERROR: No exception should have been raised for case 1.')
print(e)
else:
print('As expected, NO exception raised for case 1.')
print()
try:
p2 = Point('1', 2)
except TypeError as e:
print(e)
print(f'As expected, {type(e).__name__} exception raised for case 2.')
else:
print('ERROR: expected TypeError exception not raised for case 2')
print()
try:
p1.x = 42
except Exception as e:
print(e)
print(f'As expected, {type(e).__name__} exception raised for case 3.')
else:
print('ERROR: expected ReadOnlyError exception not raised for case 3')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)