Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Image
>>> im = Image.open("test.jpeg")
>>> data = im.load()
>>> data.__setitem__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'PixelAccess' object has no attribute '__setitem__'
>>> help(data)
>>> data.__setitem__
<method-wrapper '__setitem__' of PixelAccess object at 0x7f4d9ae4b170>
This is the strangest thing I’ve ever seen.
I’m doing a project with library PIL. ‘data‘ is an object of PixelAccess. It has the attribute of __setitem__ in help(data).
You can do ‘data[x,y] = value‘ to assign the pixel value in coordinate (x,y)
Help on PixelAccess object:
class PixelAccess(object)
| Methods defined here:
|
| __delitem__(...)
| x.__delitem__(y) <==> del x[y]
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __setitem__(...)
| x.__setitem__(i, y) <==> x[i]=y
Why doesn’t __setitem__ exist before help() function but appear after it?
It is the same even after I execute the express ‘data[x,y] = value‘. It only appears after help() function.
How to explain it?
Indeed – it is somestrange behavior.
But the problem is not that
__getitem__does not exist – it is there, just temporarily hidden due to some issue in PIL code – probably a bug resulting from the mechanisms that allow lazy loading an image.This should not trouble you – the “data” in your case is a PIL’s “PixelAccess” object, which allows you to access your image pixels using tuples as indexes. It does show “empty” when performing a “dir” on it, and will raise an attribute error if you try to get its
__getitem__method, indeed:as I said, thats ir likely a side effect of whatever mechanisms PIL uses
to create the PixelAcces object.
If you really need access to your
PixelAccess.__getitem__method, the way to get itis the way to bypass most attribute hidding tricks in Python: you do use
the
objectclass__getattribute__method to retrieve it.(And once it is done this way, surprise, the PixelAccess object no longer appears empty to dir):
All in all, the
object.__getattribute__call as shown above should be “deterministic” for you to fetch the method.As for what mechanisms it is hidden prior to that, and what causes it, and all other members of the object, to show up after introspected in this form, the only way to know is digging into PIL’s code.