什么是python描述符: 類里面有
__get__
或
__set__
或
__del__
的就叫描述符
屬性查找優先級
- 類屬性
-
數據描述符 (同時實現
__get__
和__set__
) - 實例屬性
-
非數據描述符 (只實現
__get__
) -
__getattr__
通過代理和描述符實現屬性懶加載
這里是使用裝飾器的方式實現的懶加載。可以將耗時的操作放到方法里面。在未使用的時候是一個方法,當第一次使用過后就會替換掉方法,并為之設置屬性值。
注意,只有在使用的時候才會執行函數里面的代碼,并且只執行一次,再次使用的時候直接返回值
關鍵代碼:
value
=
self
.
method
(
instance
)
setattr
(
instance
,
self
.
method_name
,
value
)
.
.
.
@LazyLoad
def
resource
(
self
)
:
代碼如下:
from
functools
import
update_wrapper
class
LazyLoad
(
object
)
:
def
__init__
(
self
,
method
)
:
self
.
method
=
method
self
.
method_name
=
method
.
__name__
update_wrapper
(
self
,
self
.
method
)
def
__get__
(
self
,
instance
,
owner
)
:
print
"-+"
*
20
print
"__get__"
print
self
,
instance
,
owner
value
=
self
.
method
(
instance
)
setattr
(
instance
,
self
.
method_name
,
value
)
print
"-+"
*
20
return
value
class
T2
(
object
)
:
def
__init__
(
self
)
:
self
.
_t
=
1
@LazyLoad
def
resource
(
self
)
:
print
"execute it in resource !"
z
=
[
str
(
i
)
for
i
in
range
(
0
,
10
)
]
return
","
.
join
(
z
)
t2
=
T2
(
)
print
type
(
t2
.
resource
)
print
t2
.
resource
print
t2
.
resource
使用裝飾器和非數據描述自定義實現
staticmethod
class
StaticObj
(
object
)
:
"""這里是自定義的非數據描述符"""
def
__init__
(
self
,
method
)
:
self
.
method
=
method
def
__get__
(
self
,
instance
,
owner
)
:
return
self
.
method
def
static_m
(
func
)
:
return
StaticObj
(
func
)
class
T3
(
object
)
:
def
__init__
(
self
)
:
print
"create it "
@static_m
def
test
(
a
,
b
)
:
print
1
,
a
,
b
print
T3
.
test
(
2
,
3
)
# 輸出 1 2 3
可以像下面一樣理解
-
test
經過裝飾器后,就是StaticObj(test)
-
然后點操作會執行
__get__
返回 test 函數,此函數是不需要綁定的 -
后面的
(2,3)
會執行 test(2,3)
看不懂沒關系,歡迎評論區討論呦~~
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
