python - Python:只允许设置具有@property 装饰器的属性
问题描述
class MyClass():
def __init__(self):
self.attribute_1 = "foo"
self.attribute_2 = "bar"
@property
def attribute_1(self):
return self._attribute_1
@attribute_1.setter
def attribute_1(self,s):
self._attribute_1 = s
@property
def attribute_2(self):
return self._attribute_2
@attribute_2.setter
def attribute_2(self,s):
self._attribute_2 = s
>>> ob = MyClass()
>>> ob.attribute_1 = 'fizz' #Ok
>>> ob.atribute_1 = 'buzz' #want to throw an exception because this has no setter or @property def
如果我们尝试设置一个没有用 property 和 setter 修饰的属性,我希望我的班级抱怨。我曾尝试使用插槽,但无法使其与属性装饰器一起使用。'attribute' in __slots__ conflicts with class variable
有什么想法吗?
解决方案
__slots__
应该包含所有实例变量,在你的情况下它是_attribute_1
和_attribute_2
(内部使用下划线的那些)所以就这样做:
class MyClass():
__slots__ = ["_attribute_1", "_attribute_2"]
pass # rest of implementation
请注意,如果您的属性只是直接转发,您不妨将公共变量放在插槽中,并且仅具有需要更多验证或其他逻辑的字段的属性。拥有插槽实际上是一种属性:
>>> MyClass._attribute_1
<member '_attribute_1' of 'MyClass' objects>
推荐阅读
- python-3.x - 无法使用核心 tensorflow api 为张量“Placeholder_1:0”提供形状 (242,) 的值
- xamarin.android - 如何在 Visual Studio 2019 中定位 Android 4.1?
- ios - 获取 imagePaths 的所有资产
- javascript - 向站点添加了一些代码,它可以正常工作,但似乎无限滚动到页脚之外
- php - 使用 POSTMAN 测试 Laravel API 路由
- c# - 如何在 C# 中使用 Process.Start 传递 argv[0]
- c# - 具有相同类和相同类列表的 C# 泛型
- rust - 如何在 Rust 中获取进位标志的值
- jquery - 从远程 url 使用 JSON 创建 Dyantable
- firebase - 列表的 MapView.Markers 未在渲染时显示