Module (93%)
Section (29%)

Look at the code presented in the editor pane.

Something that’s worth commenting on is that we have delivered:

  • a static, dedicated method for checking argument types. As we have delegated this responsibility to only one method, the code will be shorter, cleaner and easier to maintain. We'll make use of this method a few times. In case the argument's type is not an integer, a ValueError exception is raised;
  • an overridden method __setitem__, which is a magic method (mind the underscores) responsible for inserting (overwriting) an element at a given position. This method calls the check_value_type() method and later calls the genuine method __setitem__ which comes from the parent class, which does the rest of the job (sets the validated value at a given position). Now you can sigh – “oh, what a great ability!”
  • an overridden method, append(), which is responsible for appending an element to the end of the list. This method follows the previous way of dealing with a new element;
  • an overridden method, extend(), to verify and add a collection of elements to the object.

What have we not delivered?

  • All the remaining methods have remained unchanged, so our new list-like class will still behave like its parent in those places.

To make our newly-created class fully functional, it’s necessary to deliver implementations for the methods:

  • insert(index, object)
  • __add__()

These implementations should be fairly similar to the implementations delivered above (validate the type and then call the corresponding superclass method).


Code

class IntegerList(list):

@staticmethod
def check_value_type(value):
if type(value) is not int:
raise ValueError('Not an integer type')

def __setitem__(self, index, value):
IntegerList.check_value_type(value)
list.__setitem__(self, index, value)

def append(self, value):
IntegerList.check_value_type(value)
list.append(self, value)

def extend(self, iterable):
for element in iterable:
IntegerList.check_value_type(element)

list.extend(self, iterable)


int_list = IntegerList()

int_list.append(66)
int_list.append(22)
print('Appending int elements succeed:', int_list)

int_list[0] = 49
print('Inserting int element succeed:', int_list)

int_list.extend([2, 3])
print('Extending with int elements succeed:', int_list)

try:
int_list.append('8-10')
except ValueError:
print('Appending string failed')

try:
int_list[0] = '10/11'
except ValueError:
print('Inserting string failed')

try:
int_list.extend([997, '10/11'])
except ValueError:
print('Extending with ineligible element failed')

print('Final result:', int_list)
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×