Simple Object assignment giving me errors

Chris Angelico rosuav at gmail.com
Wed Feb 12 16:26:36 EST 2014


On Thu, Feb 13, 2014 at 8:18 AM, Nir <nirchernia at gmail.com> wrote:
> class FileInfo(UserDict):
>         def __init__(self, filename=None):
>                 UserDict.__init__(self)
>                 self["name"] = filename
>
> I get a TypeError: 'FileInfo' object doesn't support item assignment .
>
> Am I missing something?

You can't use square-brackets notation like that, unless you've
written your class specifically to handle it. More likely, what you
want is one of:

self.name = filename
self.dict["name"] = filename

Also, the same problem will occur with the UserDict, which tries to
update itself rather than its dict.

Actually, a simpler solution might be to have UserDict inherit from
dict. I'm not sure what you're trying to achieve here; more detail
would help. But if UserDict really is a dict, then you can call
self.update, and you can use square-brackets item assignment. I've no
idea what you'd gain over just using a dict though.

ChrisA



More information about the Python-list mailing list