Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #66104
| References | <d7d2865e-4184-4c05-b1bd-b4f16547b2f2@googlegroups.com> <5697d584-28ba-44e6-a60a-cb5ff9ae19aa@googlegroups.com> |
|---|---|
| Date | 2014-02-12 17:09 -0500 |
| Subject | Re: Simple Object assignment giving me errors |
| From | Jerry Hill <malaclypse2@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.6799.1392242945.18130.python-list@python.org> (permalink) |
On Wed, Feb 12, 2014 at 4:42 PM, Nir <nirchernia@gmail.com> wrote:
> If this makes sense to you, great. I am trying to break it down so that I can make sense of it. As you mentioned self["name"] = filename doesn't work unless I built a class to handle it. I guess my question then, is how is the class handling it in this code? If you can show me by stripping it down to the bare minimum or write an example that would be awesome.
This example works because the UserDict object being used in this code
was built to handle it. The UserDict class in the standard library
does a lot more than the little snippet you had in your original code.
Your original code would work if you did the same thing, like this:
from collections import UserDict
class FileInfo(UserDict):
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
jeez = FileInfo("yo")
(If you're using Python 2, then the first line should be "from
UserDict import UserDict" instead).
You can take a look at the source code for the userDict class here:
http://hg.python.org/cpython/file/3.3/Lib/collections/__init__.py#l862
. In that class, the code responsible for handling the bracketed name
lookup (i.e., self["name"]), is in the __getitem__ and __setitem__
methods (and peripherally in __delitem__, __len__ and __contains__)
--
Jerry
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Simple Object assignment giving me errors Nir <nirchernia@gmail.com> - 2014-02-12 13:18 -0800
Re: Simple Object assignment giving me errors Chris Angelico <rosuav@gmail.com> - 2014-02-13 08:26 +1100
Re:Simple Object assignment giving me errors Dave Angel <davea@davea.name> - 2014-02-12 16:41 -0500
Re: Simple Object assignment giving me errors Nir <nirchernia@gmail.com> - 2014-02-12 13:42 -0800
Re: Simple Object assignment giving me errors Chris Angelico <rosuav@gmail.com> - 2014-02-13 08:48 +1100
Re: Simple Object assignment giving me errors Jerry Hill <malaclypse2@gmail.com> - 2014-02-12 17:09 -0500
Re: Simple Object assignment giving me errors Nir <nirchernia@gmail.com> - 2014-02-12 14:25 -0800
csiph-web