So knowing what an iterator is, I'm assumign a string is an iterable object because the following is possible:
for c in str:
print c
I am subclassing str and overriding __hash__ and __eq__. In __hash__, I am trying to iterate over the string as follows:
for c in self.__str__:
The following error however returns: TypeError: 'method-wrapper' object is not iterable. This means that __str__ is not iterable. How do I get an iterable version of the string? I tried looking up some sort of str object API on Python but Python's documentation only shows you how to use a string, and not what the internals are, and which object in str is iterable.
How can I iterate through my subclassed string, within my string object?
3 Answers 3
Just for c in self should do. Since self is a string, you get iteration over the characters.
for c in self.__str__ does not work, because __str__ is a method, which you'd have to call (but that's useless in this case).
Comments
__str__ is another hook method, and not the value of the string.
If this is a subclass of str, you can just iterate over self instead:
for c in self:
or you can make it more explicit:
for c in iter(self):
If this is not a subclass, perhaps you meant to call __str__():
for c in self.__str__():
or you can avoid calling the hook and use str():
for c in str(self):
2 Comments
str object doc page? Not the page that teaches me how to use a string, but the actual doc page with all the methods etc...str is part of the sequence types, with an additional str specific methods section below it.If you explicitly need to call the __str__ hook, you can either call it by str(self) (recommended), or self.__str__() (not recommended, as a matter of style).
self.__str__ just refers to the method object of that name, rather than calling it.
__str__