-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrings.py
More file actions
54 lines (43 loc) · 1.68 KB
/
strings.py
File metadata and controls
54 lines (43 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class CustomString:
def __init__(self, text):
self.text = text
def __str__(self):
# User-friendly string
return f"CustomString: {self.text}"
def __repr__(self):
# Developer-friendly representation; could be used to recreate the object
return f"CustomString({self.text!r})"
def __unicode__(self):
# In Python 3 this is less used; __str__ already returns a Unicode string.
return self.text
def __format__(self, format_spec):
# Return formatted string; for example, center text in a given width
return format(self.text, format_spec)
def __hash__(self):
return hash(self.text)
def __bool__(self):
# For boolean context; empty text returns False
return bool(self.text)
def __dir__(self):
# Return a custom list of attribute names (for interactive use)
return ["text"]
def __sizeof__(self):
# Return the size in bytes (for demonstration, simply length of text)
return len(self.text)
cs = CustomString("Hello, World!")
print("str:", str(cs)) # str: CustomString: Hello, World!
print("repr:", repr(cs)) # repr: CustomString('Hello, World!')
print("Formatted:", format(cs, "^20")) # Formatted: Hello, World!
print("Hash:", hash(cs)) # Hash: 1260280734326764466
print("Bool:", bool(cs)) # Bool: True
print("dir:", dir(cs)) # dir: ['text']
print("Size (approx):", cs.__sizeof__(), "bytes") # Size (approx): 13 bytes
"""
str: CustomString: Hello, World!
repr: CustomString('Hello, World!')
Formatted: Hello, World!
Hash: 1260280734326764466
Bool: True
dir: ['text']
Size (approx): 13 bytes
"""