-
Notifications
You must be signed in to change notification settings - Fork 3
/
ClassFactory.py
executable file
·84 lines (64 loc) · 1.91 KB
/
ClassFactory.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
77
78
79
80
81
82
83
84
#! /usr/bin/env python
"""Implement an example of a base class factory function."""
def CreateClass(name, fields, parents=(), frozen=False):
"""Create a base class with a given fields and parents."""
def getter(field):
return lambda self: getattr(self, '_{}'.format(field))
def setter(field):
return lambda self, value: setattr(self, '_{}'.format(field), value)
def deleter(field):
return lambda self: delattr(self, '_{}'.format(field))
def init(self, **kwargs):
for field in fields:
if field not in kwargs:
raise ValueError(
'Missing initial value for argument "{}"'.format(field)
)
setattr(self, '_{}'.format(field), kwargs[field])
members = {'__init__': init}
for field in fields:
if frozen:
members[field] = property(
getter(field)
)
else:
members[field] = property(
getter(field),
setter(field),
deleter(field)
)
globals()[name] = type(name, parents, members)
return globals()[name]
def example_frozen_class():
"""Implement example of frozen class."""
CreateClass('Author', (
'name',
'desc'
), frozen=True)
author = Author(
name='VictorB',
desc='Engineer'
)
print(author.name)
print(author.desc)
try:
author.desc = 'Scientist'
except AttributeError:
print('You cannot set this attribute (read-only).')
def example_unfrozen_class():
"""Implement example of unfrozen class."""
CreateClass('Author', (
'name',
'desc'
))
author = Author(
name='VictorB',
desc='Engineer'
)
print(author.name)
print(author.desc)
author.desc = 'Scientist'
print(author.desc)
example_frozen_class()
print()
example_unfrozen_class()