Python Glossary Русский

Python 3.0+collectionsterm

collections.UserString

type wrappers

A str wrapper exposing its contents via .data; a base for custom string classes.

Syntax

class MyStr(collections.UserString): ...

The difference from subclassing str: on a str subclass methods like upper(), strip() and slicing hand back a plain string, so your class evaporates after the first operation, whereas UserString rebuilds each result as self.__class__ from .data. The usual User* price applies — isinstance(s, str) is False and every call goes through an extra layer — so convert with str(s) before handing the value to outside code.

Examples

from collections import UserString
s = UserString('ab')
print(s.upper(), len(s))   # → AB 2
print(s.data, type(s.data).__name__)   # → ab str
print(s == 'ab', isinstance(s, str))   # → True False
print(s + 'c', type(s + 'c').__name__)   # → abc UserString

See also

Open in the full glossarydocs.python.orgReport an inaccuracy