I would like to implement something that would work like this:
memo = Note("memo",5)
report = Note("report",20)
notebook = Notebook(memo,report)
print str(notebook.memo) # 5 expected
print str(notebook.report) # 20 expected
Inspired by: http://znasibov.info/blog/html/2010/03/10/python-classes-dynamic-properties.html and How to implement property() with dynamic name (in python) , I implemented the following code:
class Note:
def __init__(self,name,size):
self.name = name
self.size = size
class Notebook(object):
def __new__(cls,*notes):
notebook = object.__new__(cls)
setattr(notebook,'_notes',{note.name : note.size for note in notes})
functions = [lambda notebook : notebook._notes[note.name] for note in notes]
for note,function in zip(notes,functions) :
#version 1
setattr(notebook.__class__, note.name, property(function))
#version 2 -- note : __class__ removed
#setattr(notebook, note.name, property(function))
return notebook
note: I know for this minimal code use of __new__
instead of __init__
is not justified, but this will be required later on when I use subclasses of Notebook
If I use version 1:
1. instead of having 5
and 20
being printed, it prints 20
and 20
. I do not get why. Printing the functions shows an array of functions with different addresses.
2. I used __class__
inspired by the blog entry given above, but I am not sure what it does. It makes the property a class property ? (which would be real bad in my case)
If I use version 2:
prints something like property object at 0x7fb86a9d9b50
.
This seems to make sense, but I am not sure I understand why it does not print the same thing for version 1.
Is there a way to fix this, using either version (or another completely different approach) ?
Edit
An interesting answer for solving the issue was proposed. Here the corresponding code:
class Note:
def __init__(self,name,value):
self.name = name
self.size = value
def _get_size(self,notebook_class=None): return self.size+1
class Notebook(object):
def __new__(cls,*notes):
notebook = object.__new__(cls)
notebook._notes = {note.name : note.size for note in notes}
for note in notes : setattr(notebook.__class__, note.name, property(note._get_size))
return notebook
Issue is : now this test code is not giving the desired output:
memo1 = Note("memo",5)
report1 = Note("report",20)
notebook1 = Notebook(memo1,report1)
print str(notebook1.memo) # print 6 as expected (function of Note return size+1)
print str(notebook1.report) # print 21 as expected
memo2 = Note("memo",35)
report2 = Note("report",40)
notebook2 = Notebook(memo2,report2)
print str(notebook2.memo) # print 36 as expected
print str(notebook2.report) # print 41 expected
print str(notebook1.memo) # does not print 6 but 36 !
print str(notebook1.report) # does not print 21 but 41 !
I guess this was to be expected as the property was added to the class .... Anyway to overcome this issue ?