-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinheritance.py
More file actions
80 lines (61 loc) · 1.93 KB
/
inheritance.py
File metadata and controls
80 lines (61 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class Error(object):
def __init__(self, key, msg):
self.key = key
self.msg = msg
self.owner = None
# keep track of the owner class, e.g. APIError.BAD_AUTH
def __get__(self, instance, owner):
self.owner = owner
return self
def __call__(self, info=None):
return self.owner(self, info)
# for easier comparison with API error strings
def __eq__(self, other):
if isinstance(other, basestring):
return self.key == other
elif isinstance(other, Error):
return self is other
elif isinstance(other, TurntableError):
return self == other.error
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result == NotImplemented:
return NotImplemented
return not result
def __str__(self):
return '<%s.%s>' % (self.owner, self.key)
class TurntableError(Exception):
def __init__(self, error, info):
Exception.__init__(self, error)
self.error = error
msg = error.msg
if info:
msg += ': ' + str(info)
self.err = {'error': error.key, 'errmsg': msg}
INVALID_DOG = Error('INVALID_DOG', "This dog is invalid")
INVALID_CAT = Error('INVALID_CAT', "This cat is invalid")
class Animal(object):
@classmethod
def speak(cls):
print "Generic sound"
@classmethod
def sit_or_raise_error(cls,command):
if command != "sit":
raise getattr(TurntableError, "INVALID_%s" % cls.__name__.upper())()
class Dog(Animal):
@classmethod
def speak(cls):
print "woof"
class Cat(Animal):
@classmethod
def speak(cls):
print "miaow"
Dog.speak()
Cat.speak()
Dog.sit_or_raise_error("sit")
try:
Cat.sit_or_raise_error("scat")
except TurntableError as e:
if e.err['error'] == TurntableError.INVALID_CAT:
print "An invalid cat error was raised!"