Python의 Super() 함수의 역할을 이해할수 있는 예제

입질쾌감 물때표
class A(object):
  def save(self):
   print 'A saved'
 
class B(A):
  def save(self):
	print 'B saved'
	A.save(self)
 
class C(A):
  def save(self):
   print 'C saved'
   A.save(self)
 
class D(B, C):
  def save(self):
   print 'D saved'
   B.save(self)
   C.save(self)

a = D()
a.save()

print "----------------------------------------"

class A(object):
  def save(self):
   print 'A saved'
class B(A):
  def _save(self):
   print 'B save'
  def save(self):
   self._save()
   A.save(self)
class C(A):
  def _save(self):
   print 'C save'
  def save(self):
   self._save()
   A.save(self)
 
class D(B, C):
  def _save(self):
   print 'D saved'
  def save(self):
   self._save()
   B._save(self)
   C._save(self)
   A.save(self)
 
a = D()
a.save()

print "----------------------------------------"

class A(object):
  def save(self):
   print A
   print self
   print 'A saved'
class B(A):
  def save(self):
   print A
   print B
   print self
   print 'B saved'
   super(B, self).save()
class C(B):
  def save(self):
   print B
   print C
   print self
   print 'C saved'
   self.dics = "good"
   super(C, self).save()
class D(C):
  def save(self):
   print C
   print D
   print self
   super(D, self).save()
   print self.dics
   print 'D saved'

a = D()
a.save()

print "----------------------------------------"

a = B()
a.save()

 
각 Self의 인스턴스 객체를 추적해 보면 Super의 역할을 이해할수 있다.

관련 글

답글 남기기

이메일 주소는 공개되지 않습니다.