Python面向对象之类的封装操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python面向对象之类的封装操作。分享给大家供大家参考,具体如下:

承接上一节《Python面向对象之类和实例》,学了Student类的定义及实例化,每个实例都拥有各自的name和score。现在若需要打印一个学生的成绩,可定义函数 print_score()

该函数为类外的函数,如下:

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)
def print_score(Student):          # 外部函数print_score(Student)
  # print("%s's score is: %d" %(Student.name,Student.score))       # 普通 print 写法
  print("{0}'s score is: {1}".format(Student.name,Student.score))    # 建议使用 Python 2.7 + .format优化写法
print_score(May)
print_score(Peter)

既然Student实例本身就拥有这些数据,要访问这些数据,就没有必要从外面的函数去访问,我们可以直接在Student类的内部定义访问数据的函数。这样,就把数据给“封装”起来了。

“封装”就是将抽象得到的数据和行为(或功能)相结合,形成一个有机的整体(即类);封装的目的是增强安全性和简化编程,使用者不必了解具体的实现细节,而只是要通过外部接口,一特定的访问权限来使用类的成员。

而这些封装数据的函数是和Student类本身是关联起来的,我们称之为类的方法。那如何定义类的方法呢?

就要用到对象 self 本身,参考上例,把 print_score() 函数写为类的方法(Python2.7之后的版本,推荐.format 输出写法):

class Student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
  def print_score(self):
    print("{self.name}'s score is: {self.score}".format(self=self))    # Python 2.7 + .format优化写法
May = Student("May",90)
Peter = Student("Peter",85)

定义类的方法:除了第一个参数是self外,其他和普通函数一样。

实例调用方法:只需要在实例变量上直接调用,除了self不用传递,其他参数正常传入;注意,若类的方法仅需要self,不需要其他,调用该方法时,仅需 instance_name.function_name()

这样一来,我们从外部看Student类,就只需要知道,创建实例需要给出name和score,而如何打印,都是在Student类的内部定义的,这些数据和逻辑被“封装”起来了,调用很容易,但却不用知道内部实现的细节。

封装的另一个好处是可以给Student类增加新的方法;这边的方法也可以要求传参,如新增定义compare 函数,如下:

class Student(object):
  def __init__(self, name, score):
    self.name = name
    self.score = score
  def print_score(self):
    print("{self.name}'s score is: {self.score}".format(self=self))    # Python 2.7 + .format优化写法
  def compare(self,s):
    if self.score>s:
      print("better than %d" %(s))
    elif self.score==s:
      print("equal %d" %(s))
    else:
      print("lower than %d" %(s))
May = Student("May",90)
Peter = Student("Peter",85)
May.print_score()
Peter.print_score()
May.compare(100)
May.compare(90)
May.compare(89)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

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

相关文章

简单实现python画圆功能

简单实现python画圆功能

本文实例为大家分享了python实现画圆功能的具体代码,供大家参考,具体内容如下 import numpy as np import matplotlib.pyplot as p...

python挖矿算力测试程序详解

python挖矿算力测试程序详解

谈到比特币,我们都知道挖矿,有些人并不太明白挖矿的含义。这里的挖矿其实就是哈希的碰撞,举个简单例子: import hashlib x = 11 y = 1 #这里可以调节挖矿难度,...

Python 最强编辑器详细使用指南(PyCharm )

Python 最强编辑器详细使用指南(PyCharm )

作者:Jahongir Rahmonov 机器之心编译 参与:魔王 PyCharm 是一种 Python IDE,可以帮助程序员节约时间,提高生产效率。那么具体如何使用呢?本文从 PyC...

浅析Python装饰器以及装饰器模式

漫谈 如果作为一个Python入门,不了解Python装饰器也没什么,但是如果作为一个中级Python开发人员,如果再不对python装饰器熟稔于心的话,那么可能并没有量变积累到质变。...

解决python中画图时x,y轴名称出现中文乱码的问题

解决python中画图时x,y轴名称出现中文乱码的问题

如下所示: #-*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt from matplot...