Python 3 内置函数 - `super()`函数

Python 3 内置函数 - super()函数

0. super()`函数

  • 用于调用父类的一个方法。
  • super() 是用来解决多重继承问题的。

1. 使用方法

>>> super?

# output:
Init signature: super(self, /, *args, **kwargs)
## 使用说明
Docstring:     
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
    def meth(self, arg):
        super().meth(arg)
This works for class methods too:
class C(B):
    @classmethod
    def cmeth(cls, arg):
        super().cmeth(arg)
Type:           type
Subclasses:   

2. 使用示例

# 定义一个base类. 有一个计算平方的方法。
>>> class base:
>>>     def square(self, x):
>>>         print("square (base):", x*x)

# 定义一个类A. 有两个方法。
>>> class classA(Base):
>>>     def square(self, x):
>>>         super().square(x)
>>>     def add_one(self, x):
>>>         print(x+1)

# 生成实例
>>> a = classA()
>>> a.square(3)

# output:
square (base): 9
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值