|
| 1 | +__new__ example |
| 2 | +--------------- |
| 3 | + |
| 4 | +A little excercise for __new__ and making a new class act like a regular type. |
| 5 | + |
| 6 | +Here is a replacement for int which can only take new values between 0 and 255: |
| 7 | + |
| 8 | +:: |
| 9 | + |
| 10 | + class ConstrainedInt(int): |
| 11 | + def __new__(cls, value): |
| 12 | + value = value % 256 |
| 13 | + self = int.__new__(cls, value) |
| 14 | + return self |
| 15 | + |
| 16 | +A reminder of Magic methods: |
| 17 | +----------------------------- |
| 18 | + |
| 19 | +Magic Methods |
| 20 | + |
| 21 | +They all start with and end with '__', and do things like support operators and comparisons, and provide handlers for the object lifecycle. |
| 22 | + |
| 23 | +__cmp__(self, other) |
| 24 | + |
| 25 | +__eq__(self, other) |
| 26 | + |
| 27 | +__add__(self, other) |
| 28 | + |
| 29 | +Also, __call__, __str__, __repr__, __sizeof__, |
| 30 | +__setattr__, __getattr__, __len__, __iter__, |
| 31 | +__contains__, __lshift__, __rshift__, __xor__, |
| 32 | +__div__, __enter__, __exit__, |
| 33 | + |
| 34 | +and my personal favorite __rxor__(self,other)...... |
| 35 | + |
| 36 | +The list is really long, it's mostly important to get a flavor of how |
| 37 | +they are used in Python so you can find and implement the right one when |
| 38 | +you need it. |
| 39 | + |
| 40 | +See ``http://www.rafekettler.com/magicmethods.html`` for more |
| 41 | + |
| 42 | +Exercise |
| 43 | +--------- |
| 44 | + |
| 45 | +Our ConstrainedInt handles initialization for us, but doesn't handle |
| 46 | +modification of the value |
| 47 | + |
| 48 | +Develop ConstrainedInt until it passes all tests in |
| 49 | +``test_constrained_int.py`` |
| 50 | + |
| 51 | +:: |
| 52 | + |
| 53 | + class ConstrainedInt(int): |
| 54 | + """keeps value between 0 and 255""" |
| 55 | + def __new__(cls, value): |
| 56 | + value = value % 256 |
| 57 | + self = int.__new__(cls, value) |
| 58 | + return self |
| 59 | + |
0 commit comments