From 9d4d8c41f6ec709a43f0ebe796b1ee0465ca11ea Mon Sep 17 00:00:00 2001 From: tmeissner Date: Tue, 23 Dec 2014 23:23:33 +0100 Subject: [PATCH] added new file with examples of extending built-in types like integer --- python_3_oop/chapter06/extend_built-ins.py | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 python_3_oop/chapter06/extend_built-ins.py diff --git a/python_3_oop/chapter06/extend_built-ins.py b/python_3_oop/chapter06/extend_built-ins.py new file mode 100644 index 0000000..08aa6dd --- /dev/null +++ b/python_3_oop/chapter06/extend_built-ins.py @@ -0,0 +1,44 @@ +from collections import KeysView, ItemsView, ValuesView + + +class SillyInt(int): + + def __add__(self, num): + return 0 + + +a = SillyInt(1) +b = SillyInt(2) +print("{} + {} = {}".format(a, b, a+b)) + + +class DictSorted(dict): + + def __new__(*args, **kwargs): + new_dict = dict.__new__(*args, **kwargs) + new_dict.ordered_keys = [] + return new_dict + + def __setitem__(self, key, value): + """self[key] = value syntax""" + if key not in self.ordered_keys: + self.ordered_keys.append(key) + super().__setitem__(key, value) + + def setdefault(self, key, value): + if key not in self.ordered_keys: + self.ordered_keys.append(key) + return super().setdefault(key, value) + + def keys(self): + return KeysView(self) + + def values(self): + return ValuesView(self) + + def items(self): + return ItemsView(self) + + def __iter__(self): + """for x in self syntax""" + return self.ordered_keys.__iter__() \ No newline at end of file