簡體   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

如果我們嘗試設置一個沒有用屬性和設置器修飾的屬性,我希望我的 class 抱怨。 我曾嘗試使用插槽,但無法使其與屬性裝飾器一起使用。 '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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM