@@ -23,26 +23,24 @@ The ``if`` statement below uses the pattern ``if type(OBJECT) is types.TYPE`` to
2323 if type (r) is types.ListType:
2424 print (" object r is a list" )
2525
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 .
2727
2828.. code :: python
2929
30- import types
31-
3230 class Rectangle (object ):
3331 def __init__ (self , width , height ):
3432 self .width = width
3533 self .height = height
3634
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)
4038
41- c = Circle(2 )
4239 r = Rectangle(3 , 4 )
40+ s = Square(2 )
4341
4442 # bad
45- if type (r) is not type (c ):
43+ if type (r) is not type (s ):
4644 print (" object types do not match" )
4745
4846 Best practice
@@ -55,18 +53,21 @@ The preferred pattern for comparing types is the built-in function ``isinstance`
5553
5654.. code :: python
5755
58- import types
59-
6056 class Rectangle (object ):
6157 def __init__ (self , width , height ):
6258 self .width = width
6359 self .height = height
6460
61+ class Square (Rectangle ):
62+ def __init__ (self , length ):
63+ super (Square, self ).__init__ (length, length)
64+
6565 r = Rectangle(3 , 4 )
66+ s = Square(2 )
6667
6768 # 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 " )
7071
7172 References
7273----------
0 commit comments