Python : 将类属性定义为类的实例

本文最后更新于 2023年8月22日 下午

狠狠的套娃!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class static_property:
def __init__(self, getter):
self.__getter = getter

def __get__(self, obj, objtype):
return self.__getter(objtype)

@staticmethod
def __call__(getter_fn):
return static_property(getter_fn)
class A:
_bar = None

def __init__(self, spam):
self.spam = spam

@static_property
def bar(cls):
if cls._bar is None:
cls._bar = A(10)
return cls._bar
print(A._bar)

非常的好用


Python : 将类属性定义为类的实例
https://bainianlaoyao.github.io/2023/03/02/typecho-recovered-61-Python-将类属性定义为类的实例/
作者
百年老妖
发布于
2023年3月2日
许可协议