darksky
darksky

Reputation: 21049

Iterable String

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?

Upvotes: 1

Views: 10050

Answers (3)

Marcin
Marcin

Reputation: 49866

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.

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363777

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

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1123970

__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):

Upvotes: 1

Related Questions