forked from UWPCE-PythonCert/ProgrammingInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmangler.py
More file actions
executable file
·44 lines (31 loc) · 924 Bytes
/
mangler.py
File metadata and controls
executable file
·44 lines (31 loc) · 924 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
42
43
44
#!/usr/bin/env python3
"""
Simple metaclass example that creates upper and lower case versions of
all non-dunder class attributes
"""
class NameMangler(type): # deriving from type makes it a metaclass.
def __new__(cls, clsname, bases, _dict):
uppercase_attr = {}
for name, val in _dict.items():
if not name.startswith('__'):
uppercase_attr[name.upper()] = val
uppercase_attr[name.lower()] = val
else:
uppercase_attr[name] = val
return super().__new__(cls, clsname, bases, uppercase_attr)
class Foo(metaclass=NameMangler):
x = 1
Y = 2
# note that it works for methods, too!
class Bar(metaclass=NameMangler):
x = 1
def a_method(self):
print("in a_method")
if __name__ == "__main__":
f = Foo()
print(f.x)
print(f.X)
print(f.y)
print(f.Y)
b = Bar()
b.A_METHOD()