-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpy-descr-property.py
76 lines (48 loc) · 1.33 KB
/
py-descr-property.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
Playing around with descriptors and properties.
https://docs.python.org/3/howto/descriptor.html
"""
def f(*args):
print("f", args)
return "f-return"
class A:
# property creates a property object, with PyProperty_Type (descrobject.c),
# which has tp_descr_get = property_descr_get, which basically just calls the
# given fget function, in this case f.
x = property(f)
a = A()
print("a.x:", a.x)
# This cannot work: Descriptors are only searched in the class, not in the instance.
a.y = property(f)
print("a.y:", a.y)
# ---
class Property(property):
def __init__(self, name, desc, **kwargs):
property.__init__(self, **kwargs)
self.name = name
self.desc = desc
def __str__(self):
return "Property %s: %s" % (self.name, self.desc)
class B:
x = Property("x", "test", fget=f)
b = B()
print("b.x:", b.x)
print(b.__class__.x)
# ---
class InitBy(property):
def __init__(self, init_func):
super().__init__(fget=self.fget)
self.init_func = init_func
def fget(self, inst):
if hasattr(self, "value"):
return self.value
self.value = self.init_func()
return self.value
def init_func_test():
print("init_func_test")
return "x"
class C:
x = InitBy(init_func_test)
c = C()
print("c.x:", c.x)
print("c.x:", c.x)