(newbie) Is there a way to prevent "name redundancy" in OOP ?
Martin Miller
ggrp1.20.martineau at dfgh.net
Fri Jan 5 19:10:15 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)
While I agree that it's likely you're confusing Python objects and
names, Python *is* an interpreted language and therefore very flexible.
Here's a snippet showing one way to remove the 'redundancy'. (Be
forewarned that doing things like this is highly distasteful to some
people.)
### non-redundant example ###
import sys
class Pin:
def __init__(self, name, namespace=None):
self.name = name
if namespace == None:
# default to caller's globals
namespace = sys._getframe(1).f_globals
namespace[name] = self
Pin('aap') # create a Pin object named 'aap'
Pin('aap2') # create a Pin object named 'aap2'
print aap.name
print aap2.name
-Martin
More information about the Python-list
mailing list