简体   繁体   English

Python:只允许设置具有@property 装饰器的属性

[英]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

I would like my class to complain if we try and set an attribute that has not been decorated with property and a setter.如果我们尝试设置一个没有用属性和设置器修饰的属性,我希望我的 class 抱怨。 I have tried using slots but can't get it working with the property decorator.我曾尝试使用插槽,但无法使其与属性装饰器一起使用。 'attribute' in __slots__ conflicts with class variable

Any thoughts?有什么想法吗?

__slots__ should contain all instance variables, in your case it is _attribute_1 and _attribute_2 (the ones with underscores used internally) so just do that: __slots__应该包含所有实例变量,在您的情况下它是_attribute_1_attribute_2 (内部使用下划线的变量)所以只需这样做:

class MyClass():
   __slots__ = ["_attribute_1", "_attribute_2"]
   pass # rest of implementation

note that if your property is just directly forwarding you might as well just put the public variables in the slots and only have properties for fields that need more validation or other logic.请注意,如果您的属性只是直接转发,您不妨将公共变量放在插槽中,并且仅具有需要更多验证或其他逻辑的字段的属性。 having slots is effectively a property really:拥有插槽实际上是一种属性:

>>> MyClass._attribute_1
<member '_attribute_1' of 'MyClass' objects>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM