Skip to content

Commit badc19d

Browse files
committed
updated oo talk..
1 parent b86bd97 commit badc19d

File tree

11 files changed

+517
-620
lines changed

11 files changed

+517
-620
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+

Examples/week-06-OO/constrained_int/constrained_int_test.py renamed to Examples/week-06-OO/constrained_int/test_constrained_int.py

File renamed without changes.

Examples/week-06-OO/even_int.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
Using new to create an even integer
5+
6+
rounds the input to the nearest even integer.
7+
8+
will even convert a string to an int...
9+
10+
"""
11+
12+
class EvenInt():
13+
"""
14+
An integer that is always even
15+
"""
16+
pass
17+
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
Using new to create an always-positive even integer
5+
6+
rounds the input to the nearest even integer.
7+
8+
will even convert a string to an int...
9+
10+
"""
11+
12+
##subclassing an int
13+
class EvenInt(int):
14+
"""
15+
An integer that is always even
16+
"""
17+
def __new__(cls, val):
18+
val = round(float(val) / 2) * 2
19+
return int.__new__(cls, val)
20+

Examples/week-06-OO/mixins.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,40 @@
11
import time
22

3+
34
class LoggingMixin(object):
45
def log(self):
5-
print "%s: %s" % (time.time(), self.__repr__())
6+
print "%s: %s" % (time.time(), repr(self))
7+
68

79
class Vehicle(object):
810
def log(self):
911
print self.__repr__()
1012

13+
1114
class TwoWheeledVehicle(Vehicle):
1215
pass
1316

17+
1418
class LightVehicle(Vehicle):
1519
pass
1620

21+
1722
class HeavyVehicle(Vehicle):
1823
pass
1924

25+
2026
class Bike(TwoWheeledVehicle, LightVehicle):
2127
pass
2228

29+
2330
class MotorCycle(TwoWheeledVehicle, HeavyVehicle):
2431
pass
2532

33+
2634
class Tank(HeavyVehicle):
2735
pass
2836

37+
2938
bike = Bike()
3039
tank = Tank()
3140

Examples/week-06-OO/new_example.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
example of __new__
5+
"""
6+
7+
8+
9+
## the general case:
10+
class Test(object):
11+
def __new__(cls, arg):
12+
print "in __new__",
13+
print arg
14+
obj = object.__new__(cls, arg)
15+
obj.this = arg # but you probably don't want to do this!
16+
return obj
17+
18+
def __init__(self, arg):
19+
print "in __init__",
20+
print arg
21+
self.that = arg
22+
23+
24+
##subclassing a string
25+
26+
class CapitalString(str):
27+
"""
28+
A string class that is always capitalized...
29+
"""
30+
def __new__(cls, in_string):
31+
print "in CapitalString.__new__"
32+
return str.__new__(cls, in_string.title() )
33+
34+
# try it:
35+
if __name__ == "__main__":
36+
print CapitalString("this is a string")
37+
38+
39+
40+
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
tests for an even integer class
5+
"""
6+
7+
from even_int import EvenInt
8+
#from even_int_solution import EvenInt
9+
10+
## And some tests -- try with py.test or nosetests...
11+
def test_subclass():
12+
assert issubclass(EvenInt, int)
13+
14+
def test_instance():
15+
i = EvenInt(3)
16+
assert isinstance(i, int)
17+
18+
def test_even():
19+
assert EvenInt(4) == 4
20+
21+
def test_odd1():
22+
assert EvenInt(3) == 4
23+
24+
def test_odd2():
25+
assert EvenInt(2.99) == 2
26+
27+
def test_negative():
28+
assert EvenInt(-2) == -2
29+
30+
def test_negative_odd():
31+
assert EvenInt(-1) == -2
32+
33+
def test_negative_odd2():
34+
assert EvenInt(-1.1) == -2
35+
36+
def test_string_odd():
37+
assert EvenInt("3") == 4
38+
39+
def test_string_even():
40+
assert EvenInt("12") == 12
41+
42+
def test_string_float():
43+
assert EvenInt("4.45") == 4
44+

0 commit comments

Comments
 (0)