Re: how do i create such a thing?
From: Steven Bethard (steven.bethard_at_gmail.com)
Date: 01/30/05
- Next message: Tim Peters: "Re: pickle, cPickle, & HIGHEST_PROTOCOL"
- Previous message: Paul Rubin: "Re: ANNOUNCE: KirbyBase 1.7"
- In reply to: Pedro Werneck: "Re: how do i create such a thing?"
- Next in thread: Alex Martelli: "Re: how do i create such a thing?"
- Reply: Alex Martelli: "Re: how do i create such a thing?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 30 Jan 2005 15:52:43 -0700
Pedro Werneck wrote:
> If you need direct access to some atribute, use object.__getattribute__.
>
>>>>class DefaultAttr(object):
>
> ... def __init__(self, default):
> ... self.default = default
> ... def __getattribute__(self, name):
> ... try:
> ... value = object.__getattribute__(self, name)
> ... except AttributeError:
> ... value = self.default
> ... return value
> ...
>
>>>>x = DefaultAttr(99)
>>>>print x.a
> 99
>
>>>>x.a = 10
>>>>print x.a
> 10
Of if you only want to deal with the case where the attribute doesn't
exist, you can use getattr, which gets called when the attribute can't
be found anywhere else:
py> class DefaultAttr(object):
... def __init__(self, default):
... self.default = default
... def __getattr__(self, name):
... return self.default
...
py> x = DefaultAttr(99)
py> x.a
99
py> x.a = 10
py> x.a
10
Steve
- Next message: Tim Peters: "Re: pickle, cPickle, & HIGHEST_PROTOCOL"
- Previous message: Paul Rubin: "Re: ANNOUNCE: KirbyBase 1.7"
- In reply to: Pedro Werneck: "Re: how do i create such a thing?"
- Next in thread: Alex Martelli: "Re: how do i create such a thing?"
- Reply: Alex Martelli: "Re: how do i create such a thing?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]