Skip to content

Commit 4e55db6

Browse files
authored
Merge pull request #296 from realpython/inherit-python-string
Sample code for the `UserString` vs `str` article
2 parents 65b7518 + ac0e66c commit 4e55db6

File tree

5 files changed

+65
-0
lines changed

5 files changed

+65
-0
lines changed

inherit-python-string/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Custom Python Strings: Inheriting From str vs UserString
2+
3+
This folder provides the code examples for the article [Custom Python Strings: Inheriting From str vs UserString](https://realpython.com/inherit-python-str/).
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class LowerString(str):
2+
# This initializer doesn't work
3+
def __init__(self, string):
4+
super().__init__(string.lower())
5+
6+
7+
# class LowerString(str):
8+
# def __new__(cls, string):
9+
# instance = super().__new__(cls, string.lower())
10+
# return instance
11+
12+
13+
# from collections import UserString
14+
15+
16+
# class LowerString(UserString):
17+
# def __init__(self, string):
18+
# super().__init__(string.lower())
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from collections import UserString
2+
3+
4+
class MutableString(UserString):
5+
def __setitem__(self, index, value):
6+
data_as_list = list(self.data)
7+
data_as_list[index] = value
8+
self.data = "".join(data_as_list)
9+
10+
def __delitem__(self, index):
11+
data_as_list = list(self.data)
12+
del data_as_list[index]
13+
self.data = "".join(data_as_list)
14+
15+
def upper(self):
16+
self.data = self.data.upper()
17+
18+
def lower(self):
19+
self.data = self.data.lower()
20+
21+
def sort(self, key=None, reverse=False):
22+
self.data = "".join(sorted(self.data, key=key, reverse=reverse))
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class UpperPrintString(str):
2+
def __str__(self):
3+
return self.upper()
4+
5+
6+
# from collections import UserString
7+
8+
9+
# class UpperPrintString(UserString):
10+
# def __str__(self):
11+
# return self.upper()
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class WordCountString(str):
2+
def words(self, separator=" "):
3+
return len(self.split(separator))
4+
5+
6+
# from collections import UserString
7+
8+
9+
# class WordCountString(UserString):
10+
# def words(self, separator=" "):
11+
# return len(self.split(separator))

0 commit comments

Comments
 (0)