accessing value of a python @property -
i'm trying rework oauthlib implementation pyramid app , ran issue default values on @property
decorated class defs.
i somehow exposing property objects, , not calling/executing them.
can suggest way 'execute' these properties? seems calling fget
object/none works:
self.propertyname.fget(self)
this seems awkward though -- entire issue. seem implementing wrong way.
the context of problem, trying load values configuration dict , falling onto property of base class. basic form below, , advice on better implementation gladly accepted.
class parent(object): @property def fieldname(self): """returns tuple""" return (1, 10) class child(parent): @property def fieldname(self): """returns tuple""" return self._config.get('fieldname', parent.fieldname )
property
objects descriptors, means automatically bound instance when accessed attribute (this how methods created).
if wanted access parent property
object, bind manually calling descriptor.__get__()
method , passing in self
:
parent.fieldname.__get__(self))
the property.fget()
method original, un-decorated function object. you'd call unbound method, you'd pass in self
manually again:
parent.fieldname.fget(self)
or bind method, call:
parent.fieldname.fget.__get__(self)()
last, not least, use super()
object take care of binding you:
super(child, self).fieldname
which finds next object in mro (method resolution order) of class hierarchy has fieldname
attribute , binds explicit example above.
personally, prefer super()
option; best documents want access original, overridden property.
demo:
>>> class parent(object): ... @property ... def fieldname(self): ... """returns tuple""" ... return (1, 10) ... >>> class child(parent): ... @property ... def fieldname(self): ... """returns tuple""" ... return self._config.get( ... 'fieldname', ... super(child, self).fieldname) ... >>> child = child() >>> child._config = {} >>> child.fieldname (1, 10) >>> child._config['fieldname'] = ('foo', 'bar') >>> child.fieldname ('foo', 'bar')
Comments
Post a Comment