Methods overriding - AndrewMZ6/python_cheat_sheet GitHub Wiki

Creating new class mystr which behaves like usual str but applies math addition and multiplication operations instead of concatenation

class mystr(str):
	
	def __add__(self, value):
		return str(int(self) + int(value))

	def __mul__(self, value):
		return str(int(self)*int(value))

Now lets create two string objects and see what's the deal with addition!

s = str(3)
my_s = mystr(3)

print(s + '4')
print(my_s + '4')

### output
34
7

What about multiplication?

print(my_s*4)
print(s*4)

### output
12
3333

Changing the list indexing

class mylist(list):
	def __getitem__(self, key):
		return list.__getitem__(self, key - 1)
           # or return super().__getitem__(key - 1)

mylist = mylist(range(10))

print(mylist)
print(mylist[1], mylist[2], mylist[10])

### output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 9

Note that when using super() reference self argument is omitted