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求解平方根的方法
Mar 11 Python
python实现将html表格转换成CSV文件的方法
Jun 28 Python
python脚本监控docker容器
Apr 27 Python
利用matplotlib+numpy绘制多种绘图的方法实例
May 03 Python
Python中的Numpy矩阵操作
Aug 12 Python
Python求解正态分布置信区间教程
Nov 20 Python
TensorFlow 读取CSV数据的实例
Feb 05 Python
解决pycharm下pyuic工具使用的问题
Apr 08 Python
Jupyter notebook设置背景主题,字体大小及自动补全代码的操作
Apr 13 Python
Django分组聚合查询实例分享
Apr 29 Python
python 双循环遍历list 变量判断代码
May 04 Python
Python+Selenium自动化环境搭建与操作基础详解
Mar 13 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 CKEditor 上传图片实现代码
2009/11/06 PHP
PHP加密函数 Javascript/Js 解密函数
2013/09/23 PHP
PHP防盗链代码实例
2014/08/27 PHP
Thinkphp模板标签if和eq的区别和比较实例分析
2015/07/01 PHP
PHP比较运算符的详细介绍
2015/09/29 PHP
ThinkPHP框架表单验证操作方法
2017/07/19 PHP
PHP设计模式之工厂模式实例总结
2017/09/01 PHP
thinkPHP框架实现多表查询的方法
2018/06/14 PHP
Javascript 刷新全集常用代码
2009/11/22 Javascript
菜鸟javascript基础资料整理3 正则
2010/12/06 Javascript
jQuery实战之品牌展示列表效果
2011/04/10 Javascript
改进版通过Json对象实现深复制的方法
2012/10/24 Javascript
关于删除时的提示处理(确定删除吗)
2013/11/03 Javascript
php读取sqlite数据库入门实例代码
2014/06/25 Javascript
一段非常简单的js判断浏览器的内核
2014/08/17 Javascript
DOM基础教程之使用DOM
2015/01/19 Javascript
JavaScript 实现的checkbox经典实例分享
2016/10/16 Javascript
详谈js中数组(array)和对象(object)的区别
2017/02/27 Javascript
js截取字符串功能的实现方法
2017/09/27 Javascript
Vue中使用方法、计算属性或观察者的方法实例详解
2018/10/31 Javascript
vue实现文字横向无缝走马灯组件效果的实例代码
2019/04/09 Javascript
原生js实现each方法实例代码详解
2019/05/27 Javascript
用python代码做configure文件
2014/07/20 Python
python 计算数组中每个数字出现多少次--“Bucket”桶的思想
2017/12/19 Python
Python代码打开本地.mp4格式文件的方法
2019/01/03 Python
python-序列解包(对可迭代元素的快速取值方法)
2019/08/24 Python
Python下应用opencv 实现人脸检测功能
2019/10/24 Python
在python中求分布函数相关的包实例
2020/04/15 Python
pycharm中如何自定义设置通过“ctrl+滚轮”进行放大和缩小实现方法
2020/09/16 Python
.net面试题
2015/12/22 面试题
高级销售求职信
2014/02/21 职场文书
2015年初中教务处工作总结
2015/07/21 职场文书
建国70周年的心得体会(2篇)
2019/09/20 职场文书
详解CSS3.0(Cascading Style Sheet) 层叠级联样式表
2021/07/16 HTML / CSS
JavaScript中MutationObServer监听DOM元素详情
2021/11/27 Javascript
JS开发前端团队展示控制器来为成员引流
2022/08/14 Javascript