SHARE
TWEET

Untitled

a guest Mar 25th, 2013 86 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class A(object):
  2.     def __init__(self):
  3.         self.a = 1
  4.     def x(self):
  5.         print "A.x"
  6.     def y(self):
  7.         print "A.y"
  8.     def z(self):
  9.         print "A.z"
  10.  
  11. class B(A):
  12.     def __init__(self):
  13.         A.__init__(self)
  14.         self.a = 2
  15.         self.b = 3
  16.     def y(self):
  17.         print "B.y"
  18.     def z(self):
  19.         print "B.z"
  20.  
  21. class C(object):
  22.     def __init__(self):
  23.         self.a = 4
  24.         self.c = 5
  25.     def y(self):
  26.         print "C.y"
  27.     def z(self):
  28.         print "C.z"
  29.  
  30. class D(C, B):
  31.     def __init__(self):
  32.         C.__init__(self)
  33.         B.__init__(self)
  34.         self.d = 6
  35.     def z(self):
  36.         print "D.z"
  37.  
  38. Which __init__ methods are invoked and in which order is determined by the coding of the individual __init__ methods.
  39.  
  40. When resolving a reference to an attribute of an object that's an instance of class D, Python first searches the object's instance variables then uses a simple left-to-right, depth first search through the class hierarchy. In this case that would mean searching the class C, followed the class B and its superclasses (ie, class A, and then any superclasses it may have, et cetera).
  41.  
  42. With the definitions above if we define
  43.  
  44. obj = D()
  45.  
  46. then what is printed by each of the following statements?
  47.  
  48.     print obj.a
  49.  
  50.     print obj.b
  51.  
  52.     print obj.c
  53.  
  54.     print obj.d
  55.  
  56.     obj.x()
  57.  
  58.     obj.y()
  59.  
  60.     obj.z()
RAW Paste Data
Top