This issue tracker has been migrated to GitHub ,
and is currently read-only.
For more information,
see the GitHub FAQs in the Python's Developer Guide.
Created on 2008年04月11日 02:45 by esrever_otua, last changed 2022年04月11日 14:56 by admin. This issue is now closed.
| Messages (4) | |||
|---|---|---|---|
| msg65331 - (view) | Author: Darryl Dixon (esrever_otua) | Date: 2008年04月11日 02:45 | |
Compare:
>>> class y(file):
... def __init__(self, name):
... file.__init__(self, name)
... def __len__(self):
... self.seek(0, 2)
... return self.tell()
...
>>> n = y('/tmp/longfile')
>>> len(n)
364773376
Versus:
>>> class z:
... def __init__(self, name):
... self.f = file(name, 'r')
... def __len__(self):
... self.f.seek(0, 2)
... return self.f.tell()
...
>>> x = z('/tmp/longfile')
>>> len(x)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __len__() should return an int
Because:
>>> x = file('/tmp/longfile')
>>> type(x.tell())
<type 'long'>
|
|||
| msg65333 - (view) | Author: Benjamin Peterson (benjamin.peterson) * (Python committer) | Date: 2008年04月11日 02:58 | |
This is because y is a new-style class (because file is) and z is not.
If the return type of new-style classe's len is not an int, Python tries
to convert it, which is why that works for the first example. However,
that conversion doesn't happen in old-style classes. Try:
>>> class z(object):
... def __init__(self, name):
... self.f = file(name, 'r')
... def __len__(self):
... self.f.seek(0, 2)
... return self.f.tell()
>>> x = z('/tmp/longfile')
>>> len(x)
[Whatever it is]
|
|||
| msg65334 - (view) | Author: Darryl Dixon (esrever_otua) | Date: 2008年04月11日 03:47 | |
Thanks Benjamin, that is a very interesting feature that I can't find documented anywhere. Is there perhaps a documentation bug that can arise from this? There are various places where the differences between old and new-style classes are documented to a greater or lesser degree, eg: http://www.python.org/download/releases/2.2.3/bugs/ Is this documented somewhere currently that I missed, or could it be incorporated somewhere? thanks, D |
|||
| msg65349 - (view) | Author: Benjamin Peterson (benjamin.peterson) * (Python committer) | Date: 2008年04月11日 11:57 | |
The documentation is still not very good about documenting the differences between new and old style classes. Perhaps this is something which could go under the __len__ entry in "Special Method Names." |
|||
| History | |||
|---|---|---|---|
| Date | User | Action | Args |
| 2022年04月11日 14:56:33 | admin | set | github: 46864 |
| 2008年04月11日 11:57:17 | benjamin.peterson | set | nosy:
+ georg.brandl messages: + msg65349 |
| 2008年04月11日 03:47:33 | esrever_otua | set | messages: + msg65334 |
| 2008年04月11日 02:58:39 | benjamin.peterson | set | status: open -> closed resolution: not a bug messages: + msg65333 nosy: + benjamin.peterson |
| 2008年04月11日 02:45:14 | esrever_otua | create | |