[英]Is it a good idea to use property getter as constant variable for a class
由於Python沒有const類型。 我在類中有一些不希望被修改的屬性。
那么將屬性定義為屬性並只給它一個不帶setter的getter是一個好主意嗎? 如果不是,那是什么問題?
class Aclass:
def __init__(self):
# do some init
@property
def constA(self):
return 'abc'
非常感謝。
Ĵ
來自文檔
這個[
@property
]可以使用property()
作為修飾符輕松地創建只讀屬性。
沒有什么不妥。 常規代碼如下所示:
class Aclass:
def __init__(self):
# the underscore implies that the attribute is private
self._constA = 'abc'
@property
def constA(self):
return self._constA
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.