当前位置: 移动技术网 > IT编程>脚本编程>Python > python super()函数的基本使用

python super()函数的基本使用

2020年09月11日  | 移动技术网IT编程  | 我要评论
super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类会继承父类的所有的属性和方法,子类也可以覆盖父类同名的属性和

super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类会继承父类的所有的属性和方法,子类也可以覆盖父类同名的属性和方法。

class parent(object):
  value = "hi, parent value"
 
  def fun(self):
    print("this is from parent")
 
 
# 定义子类,继承父类
class child(parent):
  value = "hi, child value"
 
  def ffun(self):
    print("this is from child")
 
 
c = child()
c.fun()
c.ffun()
print(child.value)
 
# 输出结果
# this is from parent
# this is from child
# hi, child value

但是,有时候可能需要在子类中访问父类的一些属性,可以通过父类名直接访问父类的属性,当调用父类的方法是,需要将”self”显示的传递进去的方式。

class parent(object):
  value = "hi, parent value"
 
  def fun(self):
    print("this is from parent")
 
 
class child(parent):
  value = "hi, child value"
 
  def fun(self):
    print("this is from child")
    # 调用父类parent的fun函数方法
    parent.fun(self)
 
 
c = child()
c.fun()
 
# 输出结果
# this is from child
# this is from parent
# 实例化子类child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法

这种方式有一个不好的地方就是,需要经父类名硬编码到子类中,为了解决这个问题,可以使用python中的super关键字。

class parent(object):
  value = "hi, parent value"
 
  def fun(self):
    print("this is from parent")
 
 
class child(parent):
  value = "hi, child value"
 
  def fun(self):
    print("this is from child")
    # parent.fun(self)
    # 相当于用super的方法与上一调用父类的语句置换
    super(child, self).fun()
 
 
c = child()
c.fun()
 
# 输出结果
# this is from child
# this is from parent
# 实例化子类child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法

以上就是python super()函数的基本使用的详细内容,更多关于python super()函数的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网