Wednesday, 15 February 2012

class - Python properties: why doesn't this code run the function? -



class - Python properties: why doesn't this code run the function? -

i'm trying use properties , tried alter python documentation's code. i'd expect next print anything, doesn't. why not print anything?

class user: def getter(self, name): def get_prop(self): print 'getting {}'.format(name) homecoming getattr(self, name) homecoming get_prop def setter(self, name): def set_prop(self, value): print 'setting {} {}'.format(name, value) homecoming setattr(self, name, value) homecoming set_prop user_id = property(getter, setter) u = user() u.user_id = 10 u.user_id

there 2 reasons property doesn't work:

you need utilize new style class (by basing class on object); cannot utilize property setter otherwise (only getter supported old-style classes).

you generating accessors nested functions; need phone call outer methods generate accessors, property() function no you. such, can move functions out of class , utilize them plain functions instead.

the next code works:

def getter(name): def get_prop(self): print 'getting {}'.format(name) homecoming getattr(self, name) homecoming get_prop def setter(name): def set_prop(self, value): print 'setting {} {}'.format(name, value) homecoming setattr(self, name, value) homecoming set_prop class user(object): user_id = property(getter('_user_id'), setter('_user_id'))

note used _user_id property 'name' here, otherwise getattr(self, name) phone call trigger infinite recursion; u.user_id trigger getattr(u, 'user_id') triggers property again.

python class properties

No comments:

Post a Comment