当前位置:首页 >> 脚本专栏

Python class的继承方法代码实例

这篇文章主要介绍了Python class的继承方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

class parent(object):
   
  def implicit(self):
    print("Parent implicit()")
  def override(self):
    print("Parent override()")
  def altered(self):
    print("Parent altered()")
     
class child(parent):
   
  def override(self):
    print("Child override()")
  def altered(self):
    print("Child,Before Parent altered()")
    super(child,self).altered()
    print("Child,After Parent altered()")
     
dad=parent()
son=child()
 
dad.implicit()
son.implicit()
 
dad.override()
son.override()
 
dad.altered()
son.altered()

运行结果:

Parent implicit()
Parent implicit()
Parent override()
Child override()
Parent altered()
Child,Before Parent altered()
Parent altered()
Child,After Parent altered()

还可以写成:

class parent():
   
  def implicit(self):
    print("Parent implicit()")
  def override(self):
    print("Parent override()")
  def altered(self):
    print("Parent altered()")
     
class child(parent):
   
  def __init__(self):
    self.parent =parent()
     
  def implicit(self):
    self.parent.implicit()
     
  def override(self):
    print("Child override()")
     
  def altered(self):
    print("Child,Before Parent altered()")
    super(child,self).altered()
    print("Child,After Parent altered()")
     
dad=parent()
son=child()
 
dad.implicit()
son.implicit()
 
dad.override()
son.override()
 
dad.altered()
son.altered()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。