NEWBIE: What's the instance name?

Paul McGuire ptmcg at austin.rr.com
Mon Dec 29 02:10:15 EST 2003


<engsolnom at ipns.com> wrote in message
news:6q2vuv45lsah3epo9loa7l2tp9517makk4 at 4ax.com...
> Hi,
> I've been using constructs(?) like the below.
>
> def display(instance, start = None, end = None):
>
>     if instance.__class__.__name__ == 'UPCA':
>         do some UPCA stuff
>     if instance.__class__.__name__ == 'UPCE':
>         do some UPCE stuff
>
> launched by:
>
> lx = UPCA(sx), where sx is a string
> then:
> display(lx)
>
Why don't you just define a display() method on the UPCA and UPCE classes,
and instead of display(lx), call lx.display().  If UPCA and UPCE inherit
from a common base class (presumably with an abstract or default display()
method, but not necessarily), this is called "polymorphism".

Something like this:

class StringDisplayer(object):
    def __init__(instance, instring ):
        instance.dispString = instring

class UPCA(StringDisplayer):
    def display(instance, start = None, end = None):
        # UPCA-specific display stuff goes here

class UPCE(StringDisplayer):
    def display(instance, start = None, end = None):
        # UPCE-specific display stuff goes here

sx = "abc"
lx = UPCA(sx)
lx.display()

Your example also uses "instance" for the pointer to self, which works okay,
but is non-traditional; the conventional name for the self pointer is
"self".

In general, any time you are if-testing on the class of an object, you are
probably doing something polymorphic.  If there is common behavior also, put
this in the base StringDisplayer class, and invoke it using
"super(UPCA,instance).display()" in the display() method of the UPCA class,
and likewise in the UPCE class.






More information about the Python-list mailing list