[Tutor] The __setattr__ method

Roeland Rengelink r.b.rigilink@chello.nl
Tue, 28 Aug 2001 09:06:03 +0200


Justin Ko wrote:
> 
>         Hey everyone. I am working on a module to provide access to an mp3 file's
> ID3 tags. A class seemed to be the best way to represent the information
> represented in an ID3 tag's fields. However, i would like to be able to
> tell when the information in the tag is changed so that the information can
> be written back into the ID3 tag. This is my dilemma.
> 
>         The __init__ method reads the information from the file.
> 
>    def __init__(self, filename = ""):
>      "Initialize things to default values or read them from a file"
>      if filename != "":
>        try:
>          file = open(filename, "r")
>          file.seek(-128, 2)
>          if file.read(3) == "TAG":
>            self.filename = filename
>            self.title = file.read(30)
>            self.artist = file.read(30)
>            self.album = file.read(30)
>            self.year = file.read(4)
>            self.comment = file.read(30)
>            self.genre = self.genres[ord(file.read(1))]
>            self.modified = 0
> 
>         The __setattr__ method tells me when something is changed
> 
>    def __setattr__(self, name, value):
>      "Set class attributes"
>      self.__dict__[name] = value
>      self.__dict__['modified'] = 1
> 
>         However,  the statements in the __init__ method cause __setattr__ to be
> called.
>         So this is my question. How do I set a classes attributes without calling
> __setattr__ ? I guess it would be possible to replace all the self.variable
> = file.read( ) statements with something like self.__dict__[variable] =
> file.read( ), but that seems rather inelegant and ugly. I hope there is a
> better solution to this problem.
> 

Assigning to self.__dict__ directly is indeed the standard idiom to
bypass the __setattr__ method. Note that you only need to do

self.__dict__['modified'] = 0 

in the __init__. You can safely let the other assignments call
__setitem__.

Hope this helps

Roeland

-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"