Python怎么实现类的封装

发布时间:2021-06-04 16:39:34 作者:Leah
来源:亿速云 阅读:245

这期内容当中小编将会给大家带来有关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)
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怎么实现类的封装了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在Python中实现类的封装与继承
  2. python如何实现类之间的方法互相调用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:如何执行mysql命令行脚本

下一篇:Python3中有哪些字典内置方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》