Property with parameter...

Alex Martelli aleaxit at yahoo.com
Mon Sep 13 18:29:18 EDT 2004


Bengt Richter <bokr at oz.net> wrote:
   ...
> >Have your get method return an instance of an auxiliary class which
> Why a get method when a.Tag can return the aux class instance as a plain
> attribute? (other than that the OP mentioned 'property' and might want to
> protect against a.Tag = 23 ;-) E.g. See below.

Yes, if the OP is happy about potentially letting client code trample
over his precious a.Tag by assigning to it, and further is happy having
every instance of class A instantiating and holding an instance of a
Tags class (rather than doing it just-in-time if and when that attribute
is accessed) -- briefly, if he needs none of the advantages afforded by
properties -- then he'd be best advised to avoid using properties.


> If the OP doesn't need to protect against a.Tag = 23 etc., seems like a
> separate class for Tag might be simplest for him? I.e.,
> 
>  >>> class TagClass(object):
>  ...     def __init__(self): self.__Tags = {}
>  ...     def __getitem__(self, k): return self.__Tags.get(k, None) # per OP
>  ...     def __setitem__(self, k, v): self.__Tags[k] = v
>  ...
>  >>> class A(object):
>  ...     def __init__(self): self.Tag = TagClass()

If instances of class A need no other access to the dictionary than that
afforded to other code by the get/set-item special methods of this class
TagClass (in addition to not needing any of the potential extras of
properties), then this factoring (giving the TagClass instance whole
responsibility for handling the dict) may indeed be optimal.  More
usually, though, the coupling may usefully be closer -- and I mentioned
some other factorings that would afford that, besides the unusual one I
showed in detail which used closures to effect the coupling.

> For me, capitalized attributes kind of grate on the convention nerve
though ;-)

It's not a common convention in Python practice, agreed.  Not unheard
of, though -- I do believe it's mentioned in the style PEP, isn't it?


Alex



More information about the Python-list mailing list