(newbie) Is there a way to prevent "name redundancy" in OOP ?

Carl Banks pavlovevidence at gmail.com
Fri Jan 5 16:40:49 EST 2007


Stef Mientki wrote:
> Not sure I wrote the subject line correct,
> but the examples might explain if not clear
>
>
> *** first attempt ***
> class pin:
>    def __init__ (self):
>      self.Name  = 'Unknown Pin'
>
> aap = pin()             # create an instance
> aap.Name = 'aap'        # set it's name
> print aap.Name          # print it's name
> 			# but why should I set it's name ??
> print 'aap'		# I can just as well print a constant string !!
>                          # (ok there will be an extra check)
>
>
> *** second attempt ***
> class pin2:
>    def __init__ (self, naam):
>      self.Name  = naam
>
> aap2 = pin2('aap2')     # seems completely redundant to me.
> print aap2.Name
> print 'aap2'
>
>
> Can this be achieved without redundancy ?

No.  Simply not possible in Python.

You should consider whether there is another opportunity to eliminate
the redundancy.  For instance, it looks like these pin definitions
might end up in a dictionary of some sort (I don't know your use case).
 You could automatically generate the keys from the names like this:

_pindefs = (
    pin("aap"),
    pin("wap"),
    pin("dcr"),
    ...
)
pins = {}
for pin in _pindefs:
    pins[pin.Name] = pin

Then you access pins["aap"].  The reason I suspect the pins will end up
in a dictionary is that, in many real applications, the pin name would
often be specified in the input.  (This is very often the case whenever
people want to know the symbol an object is bound to, for any
application.)


Carl Banks




More information about the Python-list mailing list