[英]I'm trying to set up a class with methods from the same property that can be called by the same name using @property instead of the function property
[英]Property methods in not-called class
class Parrot:
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
我有上面的代碼(在這里找到),我希望了解不調用類並獲得以下結果是否有任何可用性。
>>> Parrot.voltage
<property at 0x7f19e83cdf48>
我知道通常情況下
>>> Parrot().voltage
100000
對於可用性,我的意思是Parrot.voltage
有許多可用的Parrot.voltage
方法,例如deleter, fdel, getter
等。但是,我不明白如何使用這些方法。
我想了解不調用類並獲得以下結果是否有任何可用性。
>>> Parrot.voltage
<property at 0x7f19e83cdf48>
好吧,您可以在查找類上的方法時詢問有關獲取函數的相同問題,即:
bruno@bigb:~$ python3
>>> class Foo():
... def bar(self):
... return 42
...
>>> Foo.bar
<function Foo.bar at 0x7fab209c5510>
在這個例子中,你可以保留對這個函數的引用,稍后調用它,將一個Foo
實例作為self
參數傳遞給它:
>>> f = Foo.bar
>>> foo = Foo()
>>> f(foo)
42
>>>
這實際上就是 Python 在實例上調用方法時所做的事情(使用foo.bar()
而不是Foo.bar(foo)
)。 你可以對你的property
對象做同樣的事情:
>>> class Parrot:
... def __init__(self):
... self._voltage = 100000
... @property
... def voltage(self):
... """Get the current voltage."""
... return self._voltage
...
>>> p = Parrot()
>>> Parrot.voltage.__get__(p)
100000
>>>
再說一次,這實際上是 Python 在看到以下內容時在幕后所做的事情:
>>> p.voltage
FWIW,python 的函數也是描述符,所以foo.bar()
的真正等價物實際上是Foo.bar.__get__(foo)()
所有這些看起來都沒有用,而且您通常不會以這種方式使用方法或屬性 - 您只需在實例上而不是在類上查找它們,然后讓 Python 完成繁重的工作。 但是,根據幾個簡單的概念(類、元類、可調用對象和屬性解析規則 - 包括描述符協議)實現整個對象模型,使語言高度動態化,並提供了與整個機制掛鈎並對其進行自定義的機會。 作為一個例子(我的意思是一般例子),這對於框架代碼來說特別方便,因為它大大減少了樣板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.