[Tutor] Problems with references

Martin Hjort Eriksen martin at hardcoder.dk
Wed Jun 2 03:01:20 EDT 2004


>Hi Martin,
>
>
>Let's look at two possible implementations of a class with an attribute:
>
>###
>class FirstExample:
>    names = []
>    def __init__(self):
>        pass
>    def add(self, name):
>        self.names.append(name)
>    def report(self):
>        for n in names:
>            print n
>
>
>class SecondExample:
>    def __init__(self):
>        self.names = []
>    def add(self, name):
>        self.names.append(name)
>    def report(self):
>        for n in names:
>            print n
>###
>
>Does your class definition resemble either one of these?
>
>The difference between the two here is that the FirstExample uses a shared
>"names"  class attribute.  The SecondExample uses an instance-specific
>"names"  attribute that's created anew for each instance.
>
>
>My guess is that the FirstExample's approach fits your problem
>description, but then, I guess wildly.  *grin*
>
>Please tell us a few more details on your class.  A small, simplified
>example of the problem with source code will help us a lot, since then we
>can duplicate the same problem.
>
>Good luck to you!
>
>
>
>  
>
Hello Danny

Thank you very much..that helped, my program now reacts the way I want. 
I understand what is going on in your explenation, but there is still 
one funny thing that I still do not understand.

This is how part of the class definition looked like, before I edited 
according to your recomendations:

class DiaObjectEntity:
    # attributes of the entity
    attributes = {}
   
    # keys of the entity
    keys = []

    # wheater or not it is a weak entity
    weak = 0
   
    # the name of the entity
    name = ""
   
    def __init__(self, DiaId):
        self.DiaId = DiaId



I moved the generation of the attribute "attributes" down into the 
__init__ method, and now they are instance specific, instead of shared. 
The funny thing however is the attribute name. Eventhough it is defined 
like the above, the content is still instence specific, and not shared. 
Meaning, that I have given each instance an unique name, at some point 
efter the instantiation, and that name is only hold for that instance, 
and is not given to the other instances.

/Martin



More information about the Tutor mailing list