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

Steven Bethard steven.bethard at gmail.com
Fri Jan 5 22:08:42 EST 2007


Stef Mientki wrote:
> Not sure I wrote the subject line correct,
> but the examples might explain if not clear
[snip]
> class pin2:
>   def __init__ (self, naam):
>     self.Name  = naam
> 
> aap2 = pin2('aap2')     # seems completely redundant to me.
> print aap2.Name

You can use class statements to create your instances with some 
metaclass trickery. Unlike normal assignments, class statements get 
access to the name being assigned. So you could write your class like::

     >>> class pin(object):
     ...     def __init__(self, name):
     ...         self.name = name
     ...     @classmethod
     ...     def from_class_block(cls, name, bases, block_dict):
     ...         return cls(name)
     ...

And then use class statements to create instances of the ``pin`` class::

     >>> class aap:
     ...     __metaclass__ = pin.from_class_block
     ...
     >>> print aap.name
     aap
     >>> type(aap)
     <class '__main__.pin'>

Of course, using class statements to create *instances* of a class is 
confusing. And it's more verbose than simply repeating the name when you 
call the constructor. But at least it avoids the redundancy. ;-)

STeVe



More information about the Python-list mailing list