首页 > 编程语言 > 详细

第四章 python中的面向对象设计

时间:2015-10-16 14:57:13      阅读:227      评论:0      收藏:0      [点我收藏+]

一、首先来理解几个面向对象的关键特性:

1、封装:对象可以将他们的内部状态隐藏起来。python中所有特性都是公开可用的。

2、继承:一个类可以是一个或多个类的子类。python支持多重继承,使用时需要注意继承顺序。

3、多态:实现将不同类型的类的对象进行同样对待的特性--不需要知道对象属于哪个类就能调用方法。

 

二、创建自己的类

 1 >>> class Person:           
 2 ...     def setname(self,name):
 3 ...             self.name = name
 4 ...     def getname(self):
 5 ...             return self.name
 6 ... 
 7 >>> p = Person()
 8 >>> p.setname(darren)
 9 >>> p.getname()
10 darren

很简单吧,这里有个self参数需要说明的,可以称为对象自身,它总是作为对象方法的第一个参数隐式传入!那么类中的有些方法不想被外部访问怎么办?
可以在方法前加双下划线,如下:

 1 >>> class Sercrt:
 2 ...     def greet(self):
 3 ...             print("hello,abc")
 4 ...     def __greet1(self):
 5 ...             print("i don‘t tell you ")
 6 ... 
 7 >>> s = Sercrt()
 8 >>> s.greet()
 9 hello,abc
10 >>> s.__greet1()
11 Traceback (most recent call last):
12   File "<stdin>", line 1, in <module>
13 AttributeError: Sercrt instance has no attribute __greet1

如何指定超类呢?通过子类后面跟上括号里面写入基类即可实现。

 1 >>> class Bird:       
 2 ...     def fly(self):
 3 ...             print("I want to fly more and more higher")
 4 ... 
 5 >>> class Swallow(Bird):
 6 ...     def fly(self):
 7 ...             print("Swallow can fly")
 8 ... 
 9 >>> 
10 >>> s = Swallow()    
11 >>> s.fly()
12 Swallow can fly

 

第四章 python中的面向对象设计

原文:http://www.cnblogs.com/mysql-dba/p/4885158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!