Python:只允许设置具有@属性装饰器的属性
Python: Only allow attributes to be set that have a @property decorator
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
如果我们尝试设置一个没有用 属性 和 setter 装饰的属性,我希望我的 class 能够提出异议。我试过使用 slots 但无法使用 属性 装饰器。 'attribute' in __slots__ conflicts with class variable
有什么想法吗?
__slots__
应该包含所有实例变量,在你的情况下它是 _attribute_1
和 _attribute_2
(内部使用的带下划线的变量)所以就这样做:
class MyClass():
__slots__ = ["_attribute_1", "_attribute_2"]
pass # rest of implementation
请注意,如果您的 属性 只是直接转发,您还不如将 public 变量放在插槽中,并且只具有需要更多验证或其他逻辑的字段的属性。有插槽实际上是 属性 真的:
>>> MyClass._attribute_1
<member '_attribute_1' of 'MyClass' objects>
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
如果我们尝试设置一个没有用 属性 和 setter 装饰的属性,我希望我的 class 能够提出异议。我试过使用 slots 但无法使用 属性 装饰器。 'attribute' in __slots__ conflicts with class variable
有什么想法吗?
__slots__
应该包含所有实例变量,在你的情况下它是 _attribute_1
和 _attribute_2
(内部使用的带下划线的变量)所以就这样做:
class MyClass():
__slots__ = ["_attribute_1", "_attribute_2"]
pass # rest of implementation
请注意,如果您的 属性 只是直接转发,您还不如将 public 变量放在插槽中,并且只具有需要更多验证或其他逻辑的字段的属性。有插槽实际上是 属性 真的:
>>> MyClass._attribute_1
<member '_attribute_1' of 'MyClass' objects>