Python 面向对象之类class和对象基本用法示例


Posted in Python onFebruary 02, 2020

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

类(class):定义一件事物的抽象特点,usually,类定义了事物的属性和它可以做到的性为

对象(object):是类的实例。

1.基本点

class MyClass(object):
  message = "hello,world"
  def show(self):
    print (self.message)

类名为MyClass 有一个成员变量:message,并赋予初值
类中定义了成员函数show(self),注意类中的成员函数必须带有参数self
参数self是对象本身的引用,在成员函数中可以引用self参数获得对象的信息

输出结果:

inst = Myclass() # 实例化一个MyClass 的对象
inst.show # 调用成员函数,无需传入self参数
hello,world

注: 通过在类名后面加小括号可以直接实例化类来获得对象变量,使用对象变量可以访问类的成员函数与成员变量。

2.构造函数

构造函数是一种特殊的类成员方法,主要用来创建对象初始化,python 中的类构造函数用__init__命名:

class MyClass(object):
  message = 'Hello, Developer.'
  def show(self):
    print self.message
  def __init__(self):
    print "Constructor is called"
inst = MyClass()
inst.show()
>>>

打印结果:

>>>Constructor is called
>>>Hello, Developer.

注:构造函数不能有返回值,python 中不能定义多个构造函数,但可以通过为命名参数提供默认值的方式达到用多种方式构造对象的目的。

3.析构函数

是构造的反向函数,在销毁或者释放对象时调用他们。

python 中为类定义析构函数的方法在类定义中定义一个名为__del__的没有返回值和参数的函数。

class MyClass(object):
  message = 'Hello, Developer.'
  def show(self):
    print self.message
  def __init__(self, name = "unset", color = "black"):
    print "Constructor is called with params: ",name, " ", color
  def __del__(self):
    print "Destructor is called!"
inst = MyClass()
inst.show()
inst2 = MyClass("David")
inst2.show()
del inst, inst2
inst3 = MyClass("Lisa", "Yellow")
inst3.show()
del inst3
>>>

打印结果:

Constructor is called with params:  unset   black
Hello, Developer.
Constructor is called with params:  David   black
Hello, Developer.
Destructor is called!
Destructor is called!
Constructor is called with params:  Lisa   Yellow
Hello, Developer.
Destructor is called!

4.实例成员变量

构造函数中定义self引用的变量,因此这样的成员变量在python中叫做实例成员变量。

def __init__(self, name = "unset", color = "black"):
  print "Constructor is called with params: ",name, " ", color
  self.name = name
  self.color = color

5.静态函数和类函数:

python 支持两种基于类名访问成员的函数:静态函数,类函数。
区别在于:类函数有一个隐形参数cls可以用来获取类信息。而静态函数没有该函数。
静态函数用装饰器:@staticmethod定义
类函数使用装饰器:@classmethod定义

class MyClass(object):
  message = 'Hello, Developer.'
  def show(self):
    print (self.message)
    print ("Here is %s in %s!" % (self.name, self.color))
  @staticmethod
  def printMessage():
    print ("printMessage is called")
    print (MyClass.message)
  @classmethod
  def createObj(cls, name, color):
    print ("Object will be created: %s(%s, %s)"% (cls.__name__, name, color))
    return cls(name, color)
  def __init__(self, name = "unset", color = "black"):
    print ("Constructor is called with params: ",name, " ", color)
    self.name = name
    self.color = color
  def __del__(self):
    print ("Destructor is called for %s!"% self.name)
MyClass.printMessage()
inst = MyClass.createObj( "Toby", "Red")
print (inst.message)
del inst

输出结果:

printMessage is called
Hello, Developer.
Object will be created: MyClass(Toby, Red)
Constructor is called with params:  Toby   Red
Hello, Developer.
Destructor is called for Toby!

6.私有成员

python 使用指定变量名格式的方法定义私有成员,即所有以双下划线“__”开始命名的成员都为私有成员。

class MyClass(object):
  def __init__(self, name = "unset", color = "black"):
    print "Constructor is called with params: ",name, " ", color
    self.__name = name
    self.__color = color
  def __del__(self):
    print "Destructor is called for %s!"% self.__name
inst = MyClass("Jojo", "White")
del inst

输出结果:

Constructor is called with params:  Jojo   White
Destructor is called for Jojo!

注明:书《Python 高效开发实战Django, Tornado, Flask, Twisted》总结

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

Python 相关文章推荐
对比Python中__getattr__和 __getattribute__获取属性的用法
Jun 21 Python
Windows下的Python 3.6.1的下载与安装图文详解(适合32位和64位)
Feb 21 Python
python线程中同步锁详解
Apr 27 Python
TensorFlow 模型载入方法汇总(小结)
Jun 19 Python
Flask框架信号用法实例分析
Jul 24 Python
Python FtpLib模块应用操作详解
Dec 12 Python
pytorch 实现将自己的图片数据处理成可以训练的图片类型
Jan 08 Python
Python3使用腾讯云文字识别(腾讯OCR)提取图片中的文字内容实例详解
Feb 18 Python
Python IDE环境之 新版Pycharm安装详细教程
Mar 05 Python
Windows+Anaconda3+PyTorch+PyCharm的安装教程图文详解
Apr 03 Python
用python-webdriver实现自动填表的示例代码
Jan 13 Python
全网最细 Python 格式化输出用法讲解(推荐)
Jan 18 Python
flask 框架操作MySQL数据库简单示例
Feb 02 #Python
python orm 框架中sqlalchemy用法实例详解
Feb 02 #Python
使用Python操作ArangoDB的方法步骤
Feb 02 #Python
详解有关PyCharm安装库失败的问题的解决方法
Feb 02 #Python
Python 模拟生成动态产生验证码图片的方法
Feb 01 #Python
Python递归及尾递归优化操作实例分析
Feb 01 #Python
Python异步编程之协程任务的调度操作实例分析
Feb 01 #Python
You might like
PHP 获取MSN好友列表的代码(2009-05-14测试通过)
2009/09/09 PHP
php记录搜索引擎爬行记录的实现代码
2018/03/02 PHP
使用PHPExcel导出Excel表
2018/09/08 PHP
Discuz! 6.1_jQuery兼容问题
2008/09/23 Javascript
jquery.form.js用法之清空form的方法
2014/03/07 Javascript
jQuery实用函数用法总结
2014/08/29 Javascript
JS运动基础框架实例分析
2015/03/03 Javascript
jQuery实现ajax调用WCF服务的方法(附带demo下载)
2015/12/04 Javascript
原生js的数组除重复简单实例
2016/05/24 Javascript
几行js代码实现自适应
2017/02/24 Javascript
移动端触屏幻灯片图片切换插件idangerous swiper.js
2017/04/10 Javascript
nodejs入门教程三:调用内部和外部方法示例
2017/04/24 NodeJs
jQuery.ajax向后台传递数组问题的解决方法
2017/05/12 jQuery
vuejs使用递归组件实现树形目录的方法
2017/09/30 Javascript
详解Webpack+Babel+React开发环境的搭建的方法步骤
2018/01/09 Javascript
JS插件clipboard.js实现一键复制粘贴功能
2020/12/04 Javascript
Vue中跨域及打包部署到nginx跨域设置方法
2019/08/26 Javascript
Jquery 动态添加元素并添加点击事件实现过程解析
2019/10/12 jQuery
详解如何修改 node_modules 里的文件
2020/05/22 Javascript
[00:36]DOTA2上海特级锦标赛 LGD战队宣传片
2016/03/04 DOTA
python 默认参数问题的陷阱
2016/02/29 Python
详解pyqt5 动画在QThread线程中无法运行问题
2018/05/05 Python
pygame游戏之旅 添加游戏暂停功能
2018/11/21 Python
Linux下Python安装完成后使用pip命令的详细教程
2018/11/22 Python
python将excel转换为csv的代码方法总结
2019/07/03 Python
python opencv 读取图片 返回图片某像素点的b,g,r值的实现方法
2019/07/03 Python
tensorflow 实现自定义梯度反向传播代码
2020/02/10 Python
python json.dumps中文乱码问题解决
2020/04/01 Python
Python select及selectors模块概念用法详解
2020/06/22 Python
TripAdvisor瑞典:全球领先的旅游网站
2017/12/11 全球购物
波兰灯具、照明和LED购物网站:Lampy.pl
2019/03/11 全球购物
智乐游戏测试笔试题
2014/05/21 面试题
新文化运动的基本口号
2014/06/21 职场文书
中学综治宣传月活动总结
2015/05/07 职场文书
2019升学宴主持词范本5篇
2019/10/09 职场文书
Python内置的数据类型及使用方法
2022/04/13 Python