@@ -23,26 +23,24 @@ The ``if`` statement below uses the pattern ``if type(OBJECT) is types.TYPE`` to
23
23
if type (r) is types.ListType:
24
24
print (" object r is a list" )
25
25
26
- Note that the following situation will not raise the error, although it should .
26
+ Note that the following situation will raise the error, although it shouldn't .
27
27
28
28
.. code :: python
29
29
30
- import types
31
-
32
30
class Rectangle (object ):
33
31
def __init__ (self , width , height ):
34
32
self .width = width
35
33
self .height = height
36
34
37
- class Circle ( object ):
38
- def __init__ (self , radius ):
39
- self .radius = radius
35
+ class Square ( Rectangle ):
36
+ def __init__ (self , length ):
37
+ super (Square, self ). __init__ (length, length)
40
38
41
- c = Circle(2 )
42
39
r = Rectangle(3 , 4 )
40
+ s = Square(2 )
43
41
44
42
# bad
45
- if type (r) is not type (c ):
43
+ if type (r) is not type (s ):
46
44
print (" object types do not match" )
47
45
48
46
Best practice
@@ -55,18 +53,21 @@ The preferred pattern for comparing types is the built-in function ``isinstance`
55
53
56
54
.. code :: python
57
55
58
- import types
59
-
60
56
class Rectangle (object ):
61
57
def __init__ (self , width , height ):
62
58
self .width = width
63
59
self .height = height
64
60
61
+ class Square (Rectangle ):
62
+ def __init__ (self , length ):
63
+ super (Square, self ).__init__ (length, length)
64
+
65
65
r = Rectangle(3 , 4 )
66
+ s = Square(2 )
66
67
67
68
# good
68
- if isinstance (r, types.ListType ):
69
- print (" object r is a list " )
69
+ if isinstance (s, Rectangle ):
70
+ print (" object s is a Rectangle " )
70
71
71
72
References
72
73
----------
0 commit comments