Anonymous     Python     09 Sep 2008    
 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
# -*- coding: utf-8 -*-
import sys, inspect
class Immutable(object):
def __setattr__(self, name, value):
if name in self.__dict__:
divired = inspect.currentframe(1).f_locals.get('self')
if not (divired and issubclass(type(divired), Immutable) ):
raise TypeError("Can't rebind immutable object(%s)" % name)
super(Immutable, self).__setattr__(name, value)
def __delattr__(self, name):
if name in self.__dict__:
divired = inspect.currentframe(1).f_locals.get('self')
if divired and issubclass(type(divired), Immutable):
super(Immutable, self).__delattr__(name)
else:
raise TypeError("Can't unbind immutable object(%s)" % name)
else:
raise NameError(name)
def test():
from user_modules.util import Inspectable
class T(Immutable, Inspectable):
def __init__(self):
self.f=10
self.z=2
def m(self):
self.f = 1
t=T()
print t
t.m()
print t
try:
t.z=10
except TypeError:
pass
else:
raise AssertionError
print t.z
if __name__ == "__main__":
test()