How to customize getattr(obj, prop) function ?
bruno at modulix
onurb at xiludom.gro
Thu May 18 06:22:16 EDT 2006
Pierre wrote:
> I don't want to use getattr(object, property, default_value) because
> I'm using external code and I don't want to modify or patch it. In this
> code, the call is getattr(object, property).
Seems like a perfectly valid reason !-)
> On my objects, I must provide default values depending on the property
> that was requested, the default value is not always the same.
On what does it depends ? Attribute name ? Class ? Phase of the moon ?
> And Yes I understand that obj.a is equivalent to getattr(obj, 'a') BUT
> the difference between class attribute and instance attribute... :S
If you mean you don't understand the difference between a class
attribute and an instance attribute, then it would be time to learn
Python's OO 101 - else you're in for trouble.
For short, an instance attribute has a per-instance value and is
(usually) stored in the object's __dict__, while a class attribute is
shared by all instances of the class and is (usually) stored in the
class's __dict__.
class Parrot(object):
cls_attr = 'class attribute'
def __init__(self):
self.instance_attr = 'instance attribute'
import pprint
pprint.pprint(Parrot.__dict__.items())
p = Parrot()
pprint.pprint(p.__dict__.items())
print Parrot.cls_attr
try:
print Parrot.instance_attr
except AttributeError, e:
print e
# will lookup 'cls_attr' in p, then in Parrot
print p.cls_attr
print p.instance_attr
# will create an instance attribute 'cls_attr' in
# object p, shadowing Parrot.cls_attr
p.cls_attr = 'WTF ?'
print p.cls_attr
print Parrot.cls_attr
del p.cls_attr
print p.cls_attr
print Parrot.cls_attr
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list