[英]Why python property() function is assigned to a class variable and not an instance variable?
我正在 python 中學習封裝和抽象,我遇到了屬性 function 和裝飾器。 常見的例子是這樣的。
class Celsius():
def __init__(self, temperature = 0):
self.set_temperature(temperature)
def to_fahrenheit(self):
return (self._temperature * 1.8) + 32
def get_temperature(self):
print("Getting value")
return self._temperature
def set_temperature(self, value):
if value < -273:
raise ValueError("Temperature below -273 is not possible")
print("Setting value")
self._temperature = value
temperature = property(get_temperature,set_temperature)
我不明白為什么屬性 function 將描述符分配給temperature
而不是self.temperature
。 難道不應該為實例而不是 class 創建 getter 或 setter 功能嗎?
就像是
self.temperature = property(get_temperature,set_temperature)
使用
test = Celsius()
pprint(test.__dict__)
返回實例 object 僅具有self._temperature
屬性(我們試圖將其設為私有)。 使用pprint(Celsius.__dict__)
返回實際上是 class 具有我們在使用對象時訪問的溫度屬性,據我所知,這沒有意義,因為我有興趣為實例創建功能並訪問實例屬性,而不是 class 屬性。
提前致謝:)
方法之外沒有自我。 這是定義 class 屬性。
@Barmar 在上面有一個有用的評論。
常用的class function參數self
和cls
在class函數之外是沒有的。 在這種情況下,您正在定義 class 的 static 成員。默認情況下,以這種方式定義的變量(如您的temperature =
)是 class 的 static 成員。
在此處查看有關 static 成員的一些有用提示: Are static class variables possible in Python?
但是為什么這樣的語法。 不應該將屬性分配給實例變量嗎?
請注意以下內容。 class_static_var = 4
的行為類似於某些人可能對cls.class_static_var = 4
的看法,但它與self.instance_var = 4
。 要定義實例變量,您可以使用__init__
方法
class DemoClass:
def __init__(self):
self.instance_var = 3
class_static_var = 4
您沒有解釋為什么您認為描述符必須位於實例命名空間中,而是查看文檔:
描述符是我們所說的定義
__get__()
、__set__()
或__delete__()
的任何 object。 ...描述符僅在用作 class 變量時才有效。 當放在實例中時,它們沒有效果。
因此,要使property
發揮作用,它必須是class的成員,而不是實例。
如果您有一個描述符Descriptor
和一個 class Foo
:
class Foo:
bar = Descriptor()
foo = Foo()
那么描述符協議將被調用
Foo.bar
或者
foo.bar
無論如何,這是一件好事。 每個實例都不需要攜帶對描述符的引用。 就像一個方法一樣,它將屬於class但實例可以訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.