1

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?

1
  • Of course a method object is not iterable. And you trying to iterate over one: - __str__ Commented Nov 22, 2012 at 15:10

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

Comments

1

__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

Got it, So just a question, I find Python's documentation page terrible. Where can I find the 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...
@Darksky: Look for the standard types page: str is part of the sequence types, with an additional str specific methods section below it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.