Python:面向对象
面向过程:根据业务逻辑从上到下写垒代码
面向对象:对函数进行分类和封装
函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
类:用来描述具有相同属性和方法的对象的集合,定义了该集合中每个对象共有的属性和方法。
方法重写:如果父类继承的方法不能满足子类的需求,可以对父类进行修改
创建类:
- class 类名:
- 成员变量
- 成员函数
例:
- class MyClass: #定义类
- n1 = 123456
- n2 = 'abc'
- def fun(self):
- return 'hello python!'
- c = MyClass()
- print(c.n1) #调用MyClass里面的变量n1
- print(c.n2) #调用MyClass里面的变量n2
- print(c.fun()) #调用MyClass里面的函数fun()
输出结果:
- 123456
- abc
- hello python!
定义有初始状态的类:类定义了 __init__() 方法的话,类的实例化操作会自动调用 __init__() 方法。__init__() 方法可以有参数,参数通过 __init__() 传递到类的实例化操作上
- def __init__(self):
- self.data = []
例:
- class Province:
- a = 123
- def __init__(self,name,capital):
- self.Name = name
- self.Capital = capital
- hb = Province('河北','石家庄')
- hn = Province('河南','郑州')
- print(hb.Capital)
- print(Province.a)
输出结果:
- 石家庄
123
类的使用:
例1:
- class information:
- name = ''
- age = 0
- weight = 0
- def __init__(self,n,a,w):
- self.name = n
- self.age = a
- self.weight = w
- def result(self):
- print("%s:I'am %s years old now!"%(self.name,self.age))
- i = information('pingy',20,130)
- print(i.result())
输出结果:
- pingy:I'am 20 years old now!
例2:
- class temp:
- def __init__(self):
- pass
- def __del__(self): #构建函数,在执行结束后都会执行这条函数
- print('我要释放了!')
- def func(self):
- print('go')
- def __call__(self):
- print('call')
- f1 = temp()
- f1.func() #调用func函数
- f1() #相当于执行__call__函数,只是跟普通定义的函数调用方式不一样而已
输出结果:
- go
- call
- 我要释放了!
类的继承:
例1:普通函数继承&继承函数内容并修改内容
- class father:
- def __init__(self):
- pass
- def func(self):
- print('class father')
- def Bad(self):
- print('抽烟,喝酒')
- class son(father): #继承父类
- def __init__(self):
- pass
- def temp(self):
- print('class son')
- def Bad(self): #在继承父类后并修改父类
- print('打篮球')
- res = son()
- res.temp() #调用子类中的函数
- res.func() #调用父类中的函数
- res.Bad() #修改父类函数的内容
输出结果:
- class son
- class father
- 打篮球
例2:普通函数继承,保存继承函数内容并增加内容
- class father:
- def __init__(self):
- pass
- def func(self):
- print('class father')
- def Bad(self):
- print('抽烟,喝酒')
- class son(father): #继承父类
- def __init__(self):
- pass
- def temp(self):
- print('class son')
- def Bad(self):
- father.Bad(self)
- print('打牌') #继承父类中Bad函数,并增加内容
- res = son()
- res.temp() #调用子类中的函数
- res.func() #调用父类中的函数
- res.Bad() #继承父类中Bad函数,并增加内容
输出结果:
- class son
- class father
- 抽烟,喝酒
- 打牌
例3:构建函数的继承
新式类继承方法和旧式类继承方法区别:(如下面两个例子:)
- #在2.0版本中:
>>> class A:- def __init__(self):
- print 'A'.center(10,'*')
- def save(self):
- print 'save from A'
- >>> class B(A):
- def __init__(self):
- print 'B'.center(10,'*')
- >>> class C(A):
- def __init__(self):
- print 'C'.center(10,'*')
- def save(self):
- print 'save from C'
- >>> class D(B,C):
- def __init__(self):
- print 'D'.center(10,'*')
- >>> c = D()
- ****D*****
- >>> c.save()
- save from A
- #在3.0版本中:
class A:- def __init__(self):
- print('A'.center(10,'*'))
- def save(self):
- print('save from A')
- class B(A):
- def __init__(self):
- print('B'.center(10,'*'))
- class C(A):
- def __init__(self):
- print('C'.center(10,'*'))
- def save(self):
- print('save from C')
- class D(C,B):
- def __init__(self):
- print('D'.center(10,'*'))
- c = D()
- c.save()
输出结果:
- ****D*****
- save from C
例4:旧式类继承方法
- class father:
- def __init__(self):
- print('father.__init__')
- class son(father): #继承父类
- def __init__(self):
- print('son.__init__')
- print('line'.center(30,'*'))
- father.__init__(self) #调用父类构建函数__init__函数
- res = son()
输出结果:
- son.__init__
- *************line*************
- father.__init__
例5:新式类继承方法
- #新式类继承方法
- class father(object):
- def __init__(self):
- print('father.__init__')
- class son(father): #继承父类
- def __init__(self):
- print('son.__init__')
- print('line'.center(30,'*'))
- super(son,self).__init__()
- res = son()
输出结果:
- son.__init__
- *************line*************
- father.__init__
例6:
- class information: #定义基本属性
- name = ''
- age =0
- weight = 0
- def __init__(self,n,a,w): #定义构造方法
- self.name = n
- self.age = a
- self.weight = w
- def res(self):
- print("%s: I'm %s years old and the weight is %s" %(self.name,self.age,self.weight))
- class other(information): #单继承方法
- grade = ''
- def __init__(self,n,a,w,g):
- information.__init__(self,n,a,w)
- self.grade = g
- def res(self):
- print("%s: I'm %s years old ,The weight is %s kg,grade %s" %(self.name,self.age,self.weight,self.grade))
- c = other('telnet',15,45,8)
- print(c.res())
输出结果:
- telnet: I'm 15 years old ,the weight is 45 kg,grade 8
多继承:
- class father: #创建父类
- name = ''
- age = 0
- def __init__(self,n,a): #定义构造方法
- self.name = n
- self.age = a
- def display(self):
- print("姓名:%s,年龄:%s。" %(self.name,self.age))
- result = father('jay1',10)
- print(result.display())
- print("我是分割线".center(30,'*'))
- class son1(father): #创建子类1,调用父类
- weight = 0
- def __init__(self,n,a,w):
- self.weight = w
- father.__init__(self,n,a)
- def display(self):
- print("姓名:%s,年龄:%s,体重:%s" %(self.name,self.age,self.weight))
- result = son1('jay2',20,50)
- print(result.display())
- print("我是分割线".center(30,'+'))
- class son2(son1): #创建子类2,调用子类1
- address = ''
- def __init__(self,n,a,w,add):
- self.address = add
- son1.__init__(self,n,a,w)
- def display(self):
- print("姓名:%s,年龄:%s,体重:%s,地址:%s。" %(self.name,self.age,self.weight,self.address))
- result = son2('jay3',30,60,'BeiJing')
- print(result.display())
- print("我是分割线".center(30,'-'))
- class others: #创建另外一个类others,没有调用任何类
- job = ''
- def __init__(self,j):
- self.job = j
- def display(self):
- print("工作:%s" %self.job)
- result = others('IT')
- print(result.display())
- print("我是分割线".center(30,'='))
- class another(son2,others): #创建另一个类another,调用子类2和others类,多重调用
- email = ''
- def __init__(self,n,a,w,add,j,e):
- self.email = e
- son2.__init__(self,n,a,w,add)
- others.__init__(self,j)
- def display(self):
- print("姓名:%s,年龄:%s,体重:%s,地址:%s,工作:%s,邮件:%s" %(self.name,self.age,self.weight,self.address,self.job,self.email))
- result = another('jay4',40,70,'shanghai','HR','123@qq.com')
- print(result.display())
输出结果:
- 姓名:jay1,年龄:10。
- ************我是分割线*************
- 姓名:jay2,年龄:20,体重:50
- ++++++++++++我是分割线+++++++++++++
- 姓名:jay3,年龄:30,体重:60,地址:BeiJing。
- ------------我是分割线-------------
- 工作:IT
- ============我是分割线=============
- 姓名:jay4,年龄:40,体重:70,地址:shanghai,工作:HR,邮件:123@qq.com
类的私有方法:
- class Test:
- __secretCount = 0 #私有变量
- publicCount = 0 #公开变量
- def counter(self):
- self.__secretCount += 1
- self.publicCount += 1
- print(self.__secretCount)
- result = Test()
- print(result.counter())
- print('Line'.center(30,'+'))
- print(result.publicCount)
- print('Line'.center(30,'*'))
- print(result.__secrctCount)
输出结果:
- 1
- +++++++++++++Line+++++++++++++
- 1
- *************Line*************
- Traceback (most recent call last):
- print(result.__secrctCount)
- AttributeError: 'Test' object has no attribute '__secrctCount' #报错,私有变量不能访问。
类的专有方法:
- class Test:
- name = 'pingy'
- age = 20
- weight = 50
- address = 'BeiJing'
- res = Test()
- res.job = 'IT' #新增一个对象和属性
- 1.print(res.job)
- 2.print(getattr(res,'weight')) #查看对象'weight'的属性
- 3.print(hasattr(res,'address')) #查看类中是否存在'address'对象,如果存在返回True,否则返回False
- del Test.address #删除address对象
- 4.print(hasattr(res,'address'))
- 5.print(delattr(res,'job')) #删除job
- 6.print(hasattr(res,'job')) #不存在job对象,del和delattr都是删除对象!
- res.name = 'echo' #修改name属性
- 7.print(res.name)
输出结果:
- 1.IT
- 2.50
- 3.True
- 4.False
- 5.None
- 6.False
- 7.echo
类的专用方法总结:
- hasattr(res, 'age') # 如果存在 'age' 属性返回 True。
- getattr(res, 'age') # 返回 'age' 属性的值
- setattr(res, 'age', 8) # 添加属性 'age' 值为 8
- delattr(res, 'age') # 删除属性 'age'
内置类属性:
- __dict__ : 类的属性(包含一个字典,由类的数据属性组成)
- __doc__ :类的文档字符串
- __name__: 类名
- __module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
- __bases__ : 类的所有父类构成元素(包含了一个由所有父类组成的元组)
Python:面向对象的更多相关文章
- python 面向对象初级篇
Python 面向对象(初级篇) 概述 面向过程:根据业务逻辑从上到下写垒代码 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可 面向对象:对函数进行分类和封装,让开发" ...
- Python 面向对象 基础
编程范式概述:面向过程 和 面向对象 以及函数式编程 面向过程:(Procedure Oriented)是一种以事件为中心的编程思想. 就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现 ...
- python面向对象进阶(八)
上一篇<Python 面向对象初级(七)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...
- python 面向对象(进阶篇)
上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...
- python 面向对象编程学习
1. 问题:将所有代码放入一个py文件:无法维护 方案:如果将代码才分放到多个py文件,好处: 1. 同一个名字的变量互相不影响 2.易于维护 3.引用模块: import module 2.包:解决 ...
- Python面向对象详解
Python面向对象的"怜人之处" Python的待客之道--谁能进来 Python的封装--只给你想要的 Python的继承--到处认干爹 Python的多态--说是就是
- python 面向对象和类成员和异常处理
python 面向对象 你把自己想象成一个上帝,你要创造一个星球,首先你要把它揉成一个个球,两个直径就能创造一个球 class star: '''名字(name),赤道直径(equatorial di ...
- python 面向对象学习
------Python面向对象初 下面写一个类的简单实用,以便方便理解类 #python 3.5环境,解释器在linux需要改变 #阅读手册查询readme文件 #作者:S12-陈金彭 class ...
- 初识python面向对象
一.初识python面向对象: class Person: #使用class关键字定义一个类 age=0 #类变量(静态变量) def eat(self,food): #定义一个方法 self.age ...
- python 面向对象、特殊方法与多范式、对象的属性及与其他语言的差异
1.python 面向对象 文章内容摘自:http://www.cnblogs.com/vamei/archive/2012/06/02/2532018.html 1.__init__() 创建对 ...
随机推荐
- jquery获得图片的真实大小
$(function(){ var imgSrc = $("#image").attr("src"); getImageWidth(imgSrc,functio ...
- linux -小记(2)问题:yum 安装报错"Another app is currently holding the yum lock; waiting for it to exit... ...: yum Memory : 26 M RSS (868 MB VSZ) Started: Wed Oct 26 22:48:24 2016 - 0"
yum 安装报错 "Another app is currently holding the yum lock; waiting for it to exit... The other ap ...
- php_sapi_name详解
php_sapi_name : — 返回 web 服务器和 PHP 之间的接口类型. 返回描述 PHP 所使用的接口类型(the Server API, SAPI)的小写字符串. 例如,CLI 的 P ...
- CSAPP(前言)
很久之前就听过有过CSAPP这本书的传闻了,今天终于决定上手这本神作:既然是神作,就要仔细拜读一下,今天看了一下前言部分还真的令人耳目一新,单单是前言部分就让我学习到几个新的知识点: 1.c和Java ...
- shell script练习
执行脚本的几种方式: 1. sh a.sh 或者 bash a.sh 调用的是 /bin/bash 进程执行的,所以脚本不需要执行权限. 2. 直接使用绝对路径执行, /home/script/a ...
- CRM JS 设置lookup字段 setSimpleLookupValue
function setSimpleLookupValue(LookupId, Type, Id, Name) { /// <summary> /// Sets the value for ...
- 全面了解 Linux 服务器 - 4. 查看 Linux 系统的平均负载
可使用 uptime.top.w 命令来查看. 以 uptime 命令为例: liuqian@ubuntu:~$ uptime 17:31:26 up 7:27, 2 users, load aver ...
- eclipse中如何关闭运行时自动保存?
Eclipse没有提供自动保存的功能,只能自己写脚本每隔多久保存一次,或监听修改即保存.设置方法:1.打开:preferences>run/debug>launching2.选择save ...
- C#中定义数组
C#定义数组 一.一维:int[] numbers = new int[]{1,2,3,4,5,6}; //不定长 int[] numbers = new int[3]{1,2,3};//定长 二 ...
- Server 2003序列号
windows2003 64位注册码 Windows 2003 R2 64bit Enterprise VOL Edition 企业版 MR78C-GF2CY-KC864-DTG74-VMT73 VP ...