第四章 python中的面向对象设计
2015-10-16 14:09
369 查看
一、首先来理解几个面向对象的关键特性:
1、封装:对象可以将他们的内部状态隐藏起来。python中所有特性都是公开可用的。
2、继承:一个类可以是一个或多个类的子类。python支持多重继承,使用时需要注意继承顺序。
3、多态:实现将不同类型的类的对象进行同样对待的特性--不需要知道对象属于哪个类就能调用方法。
二、创建自己的类
很简单吧,这里有个self参数需要说明的,可以称为对象自身,它总是作为对象方法的第一个参数隐式传入!那么类中的有些方法不想被外部访问怎么办?
可以在方法前加双下划线,如下:
如何指定超类呢?通过子类后面跟上括号里面写入基类即可实现。
1、构造方法:创建一个新对象时,调用构造方法,用于类的初始化
python中用__init__()表示构造方法,当子类继承父类时,如果子类重写了构造方法,这时如果要继承父类的构造方法,需要用super(子类,self).__init__()
2、属性:porperty(get,set)
3、静态方法和类成员方法:这两种方法无需创建对象,直接通过类名称进行调用,如下:
1、封装:对象可以将他们的内部状态隐藏起来。python中所有特性都是公开可用的。
2、继承:一个类可以是一个或多个类的子类。python支持多重继承,使用时需要注意继承顺序。
3、多态:实现将不同类型的类的对象进行同样对待的特性--不需要知道对象属于哪个类就能调用方法。
二、创建自己的类
>>> class Person: ... def setname(self,name): ... self.name = name ... def getname(self): ... return self.name ... >>> p = Person() >>> p.setname('darren') >>> p.getname() 'darren'
很简单吧,这里有个self参数需要说明的,可以称为对象自身,它总是作为对象方法的第一个参数隐式传入!那么类中的有些方法不想被外部访问怎么办?
可以在方法前加双下划线,如下:
>>> class Sercrt: ... def greet(self): ... print("hello,abc") ... def __greet1(self): ... print("i don't tell you ") ... >>> s = Sercrt() >>> s.greet() hello,abc >>> s.__greet1() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Sercrt instance has no attribute '__greet1'
如何指定超类呢?通过子类后面跟上括号里面写入基类即可实现。
>>> class Bird: ... def fly(self): ... print("I want to fly more and more higher") ... >>> class Swallow(Bird): ... def fly(self): ... print("Swallow can fly") ... >>> >>> s = Swallow() >>> s.fly() Swallow can fly
1、构造方法:创建一个新对象时,调用构造方法,用于类的初始化
python中用__init__()表示构造方法,当子类继承父类时,如果子类重写了构造方法,这时如果要继承父类的构造方法,需要用super(子类,self).__init__()
2、属性:porperty(get,set)
3、静态方法和类成员方法:这两种方法无需创建对象,直接通过类名称进行调用,如下:
>>> class Myclass: ... @staticmethod ... def smeth(): ... print("i am static method") ... @classmethod ... def cmeth(cls): ... print("i am class method") ... >>> >>> Myclass.smeth() i am static method >>> Myclass.cmeth() i am class method
相关文章推荐
- Python-爬虫初学
- [LeetCode]题解(python):027-Remove Element
- python核心编程 练习题7.5
- [LeetCode]题解(python):026-Remove Duplicates from Sorted Array
- python rodeo遇到的GConf Error问题
- Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode 错误
- <LeetCode><Easy> 169 Majority Element
- <LeetCode><Easy> 171 Excel Sheet Column Number
- python selenium expected_conditions使用实例
- 2.Python起步(未完待续)
- 1.认识Python?
- python发送邮件(含附件)
- <LeetCode><Easy> 189 Rotate Array
- Python模块搜索路径
- 获取URL中的一级域名
- 机器学习 & python k-近邻算法
- python学习笔记 (二)
- <LeetCode><Easy> 190 Revese Bits
- Python模块中的变量和函数的作用域
- <LeetCode><Easy> 191 Number Of 1 Bit