In python, the @property
and @val.setter
is very helpful. For example:
from types import FunctionType
class Test:
def __init__(self):
self.a = 1
@property
def A(self):
print('get A')
return self.a
@A.setter
def A(self, val):
print('set A')
self.a = val
t = Test()
print(t.A)
t.A = 3
print(t.A)
It works.
Now, I want to create setProperty
and getProperty
for many variable, so I want to dynamic create those functions.
My code is:
from types import FunctionType
class Test:
def __init__(self):
self.a = 1
code = compile('@property\ndef A(self): print("get A")\nreturn self.a', '', 'exec')
FunctionType(code.co_consts[0], globals(), "A")
code = compile('@A.setter\ndef A(self, val): print("set A")\nself.a=val', '', 'exec')
FunctionType(code.co_consts[0], globals(), "A")
t = Test()
print(t.A)
t.A = 3
print(t.A)
And it reports a bug:
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/medpro/test.py", line 23, in <module>
t = Test()
File "C:/Users/Administrator/Desktop/medpro/test.py", line 7, in __init__
code = compile('@property\ndef A(self): print("get A")\nreturn self.a', '', 'exec')
File "", line 3
SyntaxError: 'return' outside function
Then, I remove print("get A")
, and another bug is reported:
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/medpro/test.py", line 24, in <module>
print(t.A)
AttributeError: 'Test' object has no attribute 'A'