Class: @property -> .__dict__

Ulrich ulrich.dorda at gmail.com
Fri Dec 16 04:11:49 EST 2011


On Dec 16, 10:03 am, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> On Fri, 16 Dec 2011 00:52:11 -0800, Ulrich wrote:
> > Good morning,
>
> > I wonder if someone could please help me out with the @property function
> > as illustrated in the following example.
>
> > class te():
> >     def __init__(self):
> >         self.a = 23
> >     @property
> >     def b(self):
> >         return 2 * self.a
> [...]
> > Could anyone please explain me why this does not work / how to get b
> > into .__dict__ / hint me to an explanation?
>
> b is a property object. Like any other assignment inside the body of the
> class, it is shared across all instances, so you won't find it in the
> instance's personal dict. You will find it in the shared class dict.
>
> t.__dict__['b']  # not found
> te.__dict__['b']  # will return the property object
>
> (By the way: it is the usual convention to start the name of a class with
> initial capital, so Te would be a better name.)
>
> To get something into the instance dict, you need to assign it onto the
> instance:
>
> t.x = 42  # puts 'x':42 into t.__dict__
>
> --
> Steven

Hi Steven,

Thanks a lot for your quick and helpful answer!


This would imply that I have to search in the dict of the class and
the dict of the instance. - works nicely.

I wonder if there is somewhere a "merge of the two" already available.

In the meantime, I came across dir()
In [7]: dir(t)
Out[7]: ['__doc__', '__init__', '__module__', 'a', 'b']

This seems to return 'a' and 'b', but now crashes

@property
def attributelist(self):
        # find all attributes to the class that are of type numpy
arrays:
        return [attr for attr in self.__dict__ if
isinstance(getattr(self, attr), numpy.ndarray)]







More information about the Python-list mailing list