Python 中的 super 用法
来源:互联网 发布:淘宝买ps4哪家店好 编辑:程序博客网 时间:2024/06/08 18:35
super被用在:
当子类需要继承父类所有的属性和方法。可以理解为,用super可以继承父类的私有属性和方法。
例1:
>>> class A(object):... def __init__(self):... self.hungry = True... def eat(self):... if self.hungry: #用到了私有的变量... print('i\'m hungry!!!')>>> class B(A):... def sing(self):... print(self.sound)>>> s = B()>>> s.eat() #eat方法用到了类A的私有变量,无法访问Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in eatAttributeError: 'B' object has no attribute 'hungry'
例2:
#增加super,就可以了。super(C,self) 等价于 A>>> class C(A):... def __init__(self):... super(C,self).__init__()... self.sound = 'love me.mp3'...>>> s = C()>>> s.eat()i'm hungry!!!
例3:
>>> class A(object):... def eat(self):... print('i\'m hungry!!!')...>>> class B(A):... def sing(self):... print('self.sound')>>> s = B()>>> s.eat() #由于eat并不是A类的私有方法,所以可以直接继承i'm hungry!!!
阅读全文
0 0
- Python 中的 super 用法
- Python中的super用法详解
- Python中的super用法详解
- python中的super()和object用法
- Python 中的继承之Super用法
- python super()用法
- 【python】super的用法
- 【Python】super的用法
- Python super 用法
- python super用法
- python super用法
- python中的super
- Python中的super使用
- python中的super()
- Python中super的用法
- Python中super的用法
- Python中super的用法
- Python中super的用法
- 关于stl优先队列重载小于运算符的问题
- <C++>析构函数、虚析构函数和构造函数
- Centos6.5集群安装mysql5.6和hive2.3
- Json拼接注意
- 元组Tuple
- Python 中的 super 用法
- 迭代输出Jquery对象
- Linux系统中软件安装的相关操作
- web前端关于浏览器兼容性
- 法师康的工人(计蒜客)
- 正则表达式写法和细节
- python中的函数(二)
- python的判断和循环
- MTU、MSS、MSL、RTT、TTL、RTO