Python面向对象之类和实例用法分析


Posted in Python onJune 08, 2019

本文实例讲述了Python面向对象之类和实例用法。分享给大家供大家参考,具体如下:

虽然 Python 是解释性语言,但是它是面向对象的,能够进行对象编程。至于何为面向对象,在此就不详说了。面向对象程序设计本身就很值得深入学习,如要了解,请参阅网上其他的资料。

面向对象最重要的概念就是类(Class)和实例(Instance),牢记 类 是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。

以Student类为例,在Python中,定义类是通过 class 关键字:

注意:Python 2.X 需要在类名后面加 (object)  这边 pass 语句表示空语句段。

class 后面紧接着是类名,即Student,类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。

class Student(object):
  pass

Python 3.X 则只需要类名,不需要加 (object)

class Student:
  pass

实例

创建实例是通过类名+()实现的(若 __init__ 无或仅有self);如定义好了Student类,就可以根据Student类创建出Student的实例,如下:

class Student(object):
  pass
May = Student()          # 新建May实例
print(May)

运行结果:

<__main__.Student object at 0x0000000001DCC400>

可以看到,变量May指向的就是一个Student的object,后面的0x006C4770是内存地址,每个object的地址都不一样,而Student本身则是一个类。

可以自由地给一个实例变量绑定属性,比如,给实例 May 绑定一个 name 属性,这个 name 属性是实例 May 特有的,其他新建的实例是没有 name 属性的

class Student(object):
  pass
May = Student()         # 新建May实例
print(May)
May.name = "May"         # 给实例 May 绑定 name 属性为 "May"
print(May.name)
Peter = Student()        # 新建Peter实例
# print(Peter.name)       # 报错,因为Peter没有Name属性

那么,如果我们需要类必须绑定属性,那如何定义呢?  请参见下文。

__init__ 构造函数

由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。 (注意 __init__ 双下划线)

如对于Student类,我们定义 name 和 score 属性(所有Sudent 都须有的属性):

__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。

有了__init__方法,在创建实例的时候,就不能传入空的参数了,必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去:

class Student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
May = Student("May",90)      # 须要提供两个属性
Peter = Student("Peter",85)
print(May.name, May.score)
print(Peter.name, Peter.score)

__del__ 析构函数

Just like the __init__ method, there is another special method __del__ which is called when an object is going to die i.e. it is no longer being used and is being returned to the computer system for reusing that piece of memory.

The __del__ method is run when the object is no longer in use and there is no guarantee when that method will be run. If you want to explicitly see it in action, we have to use the del statement which is what we have done here.

相对于 构造函数 Python 也有类似 C++ 中的析构函数 __del__ , Python的垃圾回收过程与常用语言的不一样,如果一定需要,最好需要使用del语句来激活。

私有变量

Note for C++/Java/C# Programmers
All class members (including the data members) are public and all the methods are virtual in Python.
One exception: If you use data members with names using the double underscore prefix such as __privatevar, Python uses name-mangling to effectively make it a private variable.
Thus, the convention followed is that any variable that is to be used only within the class or object should begin with an underscore and all other names are public and can be used by other classes/objects. Remember that this is only a convention and is not enforced by Python (except for the double underscore prefix).

Python 中定义私有变量,命名规则为前缀加两个下划线 “__” ,注意不可前后都包含__XXX__(该命名表示为类属性或内建变量);还有一种命名为单下划线 _XXX ,表示约定俗成不可访问的变量。

class Person(object):
  def __init__(self,name,sex):
    self.name = name
    self.__sex = sex       # sex 定义为私有变量
  def print_title(self):
    if self.sex == "male":
      print("man")
    elif self.sex == "female":
      print("woman")
May = Person("May","female")
print(May.name)    
print(May.__sex)           # 会报错

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python中os操作文件及文件路径实例汇总
Jan 15 Python
Python基于checksum计算文件是否相同的方法
Jul 09 Python
Caffe均值文件mean.binaryproto转mean.npy的方法
Jul 09 Python
Flask框架各种常见装饰器示例
Jul 17 Python
Python简单过滤字母和数字的方法小结
Jan 09 Python
python实现一行输入多个值和一行输出多个值的例子
Jul 16 Python
python list转置和前后反转的例子
Aug 26 Python
基于Python获取docx/doc文件内容代码解析
Feb 17 Python
python GUI库图形界面开发之PyQt5下拉列表框控件QComboBox详细使用方法与实例
Feb 27 Python
Python Handler处理器和自定义Opener原理详解
Mar 05 Python
Python3操作读写CSV文件使用包过程解析
Apr 10 Python
python实现Thrift服务端的方法
Apr 20 Python
Python学习笔记之自定义函数用法详解
Jun 08 #Python
Python3基础教程之递归函数简单示例
Jun 07 #Python
Python正则表达式匹配和提取IP地址
Jun 06 #Python
Python 常用模块 re 使用方法详解
Jun 06 #Python
Python比较配置文件的方法实例详解
Jun 06 #Python
Django中使用 Closure Table 储存无限分级数据
Jun 06 #Python
创建Django项目图文实例详解
Jun 06 #Python
You might like
深入理解ob_flush和flush的区别(ob_flush()与flush()使用方法)
2013/02/06 PHP
php对图像的各种处理函数代码小结
2013/07/08 PHP
php 创建以UNIX时间戳命名的文件夹(示例代码)
2014/03/08 PHP
PHP的简单跳转提示的实现详解
2019/03/14 PHP
showModelessDialog()使用详解
2006/09/07 Javascript
利用JavaScript实现新闻滚动效果(实例代码)
2013/11/27 Javascript
回车直接实现点击某按钮的效果即触发单击事件
2014/02/27 Javascript
JQuery插件iScroll实现下拉刷新,滚动翻页特效
2014/06/22 Javascript
javascript实现playfair和hill密码算法
2014/12/07 Javascript
JS+CSS实现Li列表隔行换色效果的方法
2015/02/16 Javascript
js+div实现文字滚动和图片切换效果代码
2015/08/27 Javascript
JS弹出对话框实现方法(三种方式)
2015/12/18 Javascript
js中使用使用原型(prototype)定义方法的好处详解
2016/07/04 Javascript
关于两个jQuery(js)特效冲突的bug的解决办法
2016/09/04 Javascript
JS实现页面载入时随机显示图片效果
2016/09/07 Javascript
jQuery图片轮播实现并封装(一)
2016/12/03 Javascript
谈谈第三方App接入微信登录 解读
2016/12/27 Javascript
Three.js实现浏览器变动时进行自适应的方法
2017/09/26 Javascript
详解基于vue-router的动态权限控制实现方案
2017/09/28 Javascript
完美解决手机网页中输入框被输入法遮挡的问题
2017/12/19 Javascript
使用vue-cli+webpack搭建vue开发环境的方法
2017/12/22 Javascript
Vue+Express实现登录状态权限验证的示例代码
2019/05/05 Javascript
Node使用Selenium进行前端自动化操作的代码实现
2019/10/10 Javascript
[03:09]显微镜下的DOTA2第一期——带你走进华丽的DOTA2世界
2014/06/20 DOTA
python使用cookie库操保存cookie详解
2014/03/03 Python
Python编码类型转换方法详解
2016/07/01 Python
浅谈python中的占位符
2017/11/09 Python
python matplotlib实现双Y轴的实例
2019/02/12 Python
详解Python学习之安装pandas
2019/04/16 Python
Python爬虫新手入门之初学lxml库
2020/12/20 Python
如何用JQuery进行表单验证
2013/05/29 面试题
会计自我鉴定
2014/02/04 职场文书
大学新闻系求职信
2014/06/03 职场文书
师德自我剖析材料范文
2014/10/06 职场文书
企业爱心捐款倡议书
2015/04/27 职场文书
用Python提取PDF表格的方法
2021/04/11 Python