Python学习笔记之类和对象
2017-12-17 16:31
393 查看
面向对象编程,是当前比较主流的编程方式。Python同样支持面向对象编程,在面向对象编程中,可以编写表示现实世界中的事物或者情景。在定义类时,需要对现实世界中的对象进行抽象。基于类创建对象时,是对每个现实世界中的对象进行实例化。
创建和使用类
使用类几乎可以模拟任何一样现实世界中的事物,比如我们编写一个通用的汽车类-它表示的不是一辆具体的汽车,而是任何的汽车所共有的特点中抽象出来的。创建汽车类
每辆汽车都有发动机,有颜色,有排量,可以驾驶,可以刹车,现在我们先根据这些特点来定义一个汽车的类。语法关键字
class。
class Car(): def __init__(self,color,displacement,engine): self.color = color self.displacement = displacement self.engin = engine def drive_forward(self): print('Moving forward') def drive_backward(self): print('Moving backward') def brake(self): print('Braking')
实例化以及调用方法
my_car = Car('yellow','1.6T','Sabb') print(my_car.color) my_car.drive_forward() my_car.drive_backward() my_car.brake()
继承
语法:class subclass(parentclass)
class TestCar(Car): def __init__(self, color, displacement, engine): super().__init__(color, displacement, engine) def description(self): print(self.color + self.displacement + self.engin) my_testcar = TestCar('Red', '1.8T', 'Audi') my_testcar.description()
重定义父类的方法
def drive_backward(self,speed): print('Moving back: ' + str(speed))
调用
my_testcar.drive_backward(100)
结语
在程序设计的过程中,面向对象编程的思想可以让代码的组织更加的有条理,也使复杂的项目开发进度更加迅速,在真实的项目中,面向对象的编程设计已经是主流的方法。附录 - 程序代码
class Car(): def __init__(self, color, displacement, engine): self.color = color self.displacement = displacement self.engin = engine def drive_forward(self): print('Moving forward') def drive_backward(self): print('Moving backward') def brake(self): print('Braking') my_car = Car('yellow', '1.6T', 'Sabb') print(my_car.color) my_car.drive_forward() my_car.drive_backward() my_car.brake() print('继承') class TestCar(Car): def __init__(self, color, displacement, engine): super().__init__(color, displacement, engine) def description(self): print(self.color + self.displacement + self.engin) def drive_backward(self,speed): print('Moving back: ' + str(speed)) my_testcar = TestCar('Red', '1.8T', 'Audi') my_testcar.description() my_testcar.drive_backward(100)
相关文章推荐
- Python学习笔记 - 面向对象高级编程
- 【Head First Python-第六章-定制数据对象】学习笔记
- python学习笔记十 类文件对象
- python cookbook第三版学习笔记十:类和对象(一)
- python 学习笔记7(类/对象的属性;特性,__getattr__)
- 流畅的python学习笔记:第九章:符合python风格的对象
- 【转】python类、对象、方法、属性之类与对象笔记
- python基础学习笔记5--对象
- Python核心编程--学习笔记--4--Python对象
- python学习笔记六之面向对象相关下(基础篇)
- Python学习笔记12:标准库之对象序列化(pickle包,cPickle包)
- 【Python】学习笔记——-8.1、面向对象高级编程:1.使用__slots__
- 廖雪峰Python教程 学习笔记11 面向对象高级编程
- Python学习笔记(一)json和对象之前的相互转换
- Python学习笔记:python3中的range()函数的返回对象类型
- Dive in Python学习笔记五:对象和面向对象
- DAY6之Python学习笔记:面向对象术语整理
- Python学习笔记:python3中的range()函数的返回对象类型
- python类、对象、方法、属性之类与对象笔记
- python 学习笔记 对象(4)