making objects with individual attributes!
Gary Herron
gherron at islandtraining.com
Tue Mar 20 12:25:17 EDT 2007
Alejandro wrote:
> I have created a class:
>
> class document:
>
> titre = ''
> haveWords = set()
>
> def __init__(self, string):
>
> self.titre = string
>
> #########
>
> doc1 = document('doc1')
> doc2 = document('doc2')
>
> doc1.haveWords.add(1)
> doc2.haveWords.add(2)
>
>
> print doc1.haveWords
>
> # i get set([1, 2])
>
>
> doc1 and doc are sharing attribute haveWords!
> Why ??? there's a way to assign every objetc "document" a different
> "set"
>
Of course. Try this:
class document:
def __init__(self, string):
self.titre = string
self.haveWords = set()
Each instance creation will call __init__ with the instance
accessible through self, and that code will create two instance
specific attributes.
Don't use so called class level attributes (as in your example)
unless you *want* sharing between all instances of a class.
Gary Herron
More information about the Python-list
mailing list