-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.py
More file actions
41 lines (28 loc) · 931 Bytes
/
test.py
File metadata and controls
41 lines (28 loc) · 931 Bytes
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
def define_property(
type_,
optional=False,
default_factory=None):
def decorator(func):
attr_name = f"_{func.__name__}"
@property
def prop(self):
if hasattr(self, attr_name):
return getattr(self, attr_name)
elif optional:
return default_factory() if default_factory else None
else:
raise AttributeError(f"{func.__name__} is not set.")
@prop.setter
def prop(self, value):
if not isinstance(value, type_):
raise TypeError(f"{func.__name__} must be of type {type_.__name__}.")
setattr(self, attr_name, value)
return prop
return decorator
class TestClass:
@define_property(str)
def p(self, value):
print(f'p is set to {value}')
c = TestClass()
c.p = '1'
print(c.p)