Python 类的定义和实例化,类继承
2017-09-21 12:14
197 查看
#coding=utf-8 #定义父类 用于单位转换 class ScaleConverter: def __init__(self,unit_from,unit_to,factor): #第一个参数必须是self self.unit_from=unit_from self.unit_to=unit_to self.factor=factor def description(self): #函数必须传入self,self用于区分是哪个对象调用该方法 return 'Convert '+self.unit_from+' to '+self.unit_to def convert(self,value): return value*self.factor c1=ScaleConverter('inches','mm',25) #实例化类 print(c1.description()) print(str(c1.convert(2))+c1.unit_to) #============================================================================ class ScaleAndOffsetConverter(ScaleConverter): # 定义子类,类继承 def __init__(self,unit_from,unit_to,factor,offset): ScaleConverter.__init__(self,unit_from,unit_to,factor) #通过父类的init()函数构造 self.offset=offset def convert(self,value): #覆盖父类的convert()函数 return value*self.factor+self.offset c2=ScaleAndOffsetConverter('C','F',1.8,32) #实例化类 print(c2.description()) print(str(c2.convert(20))+c2.unit_to)
相关文章推荐
- python--基础学习(二)判断 、循环、定义函数、继承、调用
- python 类的定义和继承
- 【中科大洋笔试题】定义一个不能被继承的类,并且只能实例化3个对象。
- python进阶学习笔记(四)——python中访问限制、创建类属性、定义实例方法、定义类方法、类的继承
- Python 类的定义、继承及使用对象
- 继承一个虚类的时候要小心是,并使其实例化时.必须使其全实重写了纯虚的方法...类定义的位置
- Python 类的定义、继承及使用对象
- Python 类的定义、继承及使用对象 [转]
- python 7-1 如何派生内置不可变类型(int,str,tuple,float)并修改实例化行为,继承内置tuple并实现__new__
- Python 类的定义、继承及使用对象
- Python中类的定义、继承及使用对象实例详解
- PYthon类的定义、继承以及使用对象(例)
- python 类定义 继承
- python 类定义和实例化使用
- Python中类的定义、继承及使用对象实例详解
- 定义一个类不能被继承,且只能被实例化3次
- python---面向对象,class定义、构造函数、析构函数、基本继承
- Python简化类例一:实现在类的定义、继承、重写
- 菜鸟学习abstract【一个类可以被继承但不能实例化,子类不需要重新定义属性】
- Python 类的定义、继承及使用对象