0
点赞
收藏
分享

微信扫一扫

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

安七月读书 2022-03-30 阅读 27
python

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

0. 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 条评论