python中类的创建,父子类的继承
来源:互联网 发布:西安星河网络小贷 编辑:程序博客网 时间:2024/05/19 22:27
#!/usr/bin/pythonclass Ppoint: def __init__(self, x, y): self.x = x self.y = y # def __del__(self): # class_name = self.__class__.__name__ # print class_name, "destroyed"class Spring_Point(Ppoint): def __init__(self): Ppoint.__init__(self, 1, 2) # super(Spring_Point, self).__init__(1, 2)if __name__ == "__main__": xx = Spring_Point() print xx.__dict__
以上是用old的方式来创建一个class, Ppoint, class Spring_Point继承Spring_Point, 在调用父类的构造函数的时候,必须使用
Ppoint.__init__(self, 1, 2)
不能使用
super(Spring_Point, self).__init__(1, 2)如果使用心得方式创建类
#!/usr/bin/pythonclass Ppoint(object): def __init__(self, x, y): self.x = x self.y = y # def __del__(self): # class_name = self.__class__.__name__ # print class_name, "destroyed"class Spring_Point(Ppoint): def __init__(self): Ppoint.__init__(self, 1, 2) # super(Spring_Point, self).__init__(1, 2)if __name__ == "__main__": xx = Spring_Point() print xx.__dict__
则两种调用父类构造器的方法都可以,参考http://stackoverflow.com/questions/9698614/super-raises-typeerror-must-be-type-not-classobj-for-new-style-class
In short, they are equivalent. Let's have a history view:(1) at first, the function looks like this. class MySubClass(MySuperClass): def __init__(self): MySuperClass.__init__(self)(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like: super(<class>, <instance>)And init function can be: class MySubClassBetter(MySuperClass): def __init__(self): super(MySubClassBetter, self).__init__()However requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.(3) in V3. It is more smart, super()
0 0
- python中类的创建,父子类的继承
- Python 父子类继承笔记
- Python中类的继承
- Python中类的继承
- Python中类的继承
- python 中类的继承
- Python--类的创建与继承
- Java继承关系的父子类中相同的成员变量
- Java继承关系的父子类中相同的成员变量
- C++子类继承时,父子类中含有相同的函数,为何能编译通过
- C++父子类继承时的隐藏、覆盖、重载
- python之自动生成C++的父子双向继承关系
- javascript中类的创建和继承
- iOS中,父子类控制的使用方法
- 继承时候的父子关系
- 继承、父子类、单继承、多继承
- js中es5类的创建继承与es6中类的创建继承
- 由一个简单示例 引出java继承中父子类成员变量共享问题 以及super的使用
- 二级指针的第三种内存模型
- HDU 2147 kiki's game
- POJ 2449 Remmarguts' Date K短路
- 09: Neural Networks - Learning
- 模拟电路-释疑
- python中类的创建,父子类的继承
- 在O(1)时间删除链表结点--总结
- leetcode 刷题之路 46 Set Matrix Zeroes
- java连接mongodb数据库
- 面向.Net程序员的前端优化
- 字符理论--Unicode详解
- Java经典算法大全
- Count on Canton
- Objective-C NSString