python隐藏类中属性的3种实现方法

yipeiwu_com6年前Python基础

方法一:

效果图一:

代码一:

# 定义一个矩形的类
class Rectangle:
  # 定义初始化方法
  def __init__(self,width,height):
    self.hidden_width = width
    self.hidden_height = height

  # 定义获取width、height的方法
  def get_width(self):
    return self.hidden_width

  def get_height(self):
    return self.hidden_height

  # 定义修改width、height的方法
  def set_width(self,width):
    self.hidden_width = width

  def set_height(self,height):
    self.hidden_height = height

  # 定义一个获取矩形面积的方法
  def get_area(self):
    return self.hidden_width * self.hidden_height

# 创建Rectangle的实例
r_one = Rectangle(3,4)
# 输出打印 r_one的widh
print(r_one.get_width())  # 输出 3
# 输出打印 r_one的area
print(r_one.get_area())  # 输出 12

# 改变width
r_one.set_width(5)
print(r_one.get_area())   # 输出 20

方法二:

效果图二:

代码二:

# 可以为对象的属性使用双下划线开头,__xxx
# 双下划线开头的属性,是对象的隐藏属性,隐藏属性只能在类的内部访问,无法通过对象访问
# 其实隐藏属性只不过是Python自动为属性改了一个名字
#  实际上是将名字修改为了,_类名__属性名 比如 __name -> _Person__name
class Person:
  def __init__(self,name):
    self.__name = name

  def get_name(self):
    return self.__name

  def set_name(self , name):
    self.__name = name    

p = Person('孙悟空')

# print(p.__name) # 报错:AttributeError: 'Person' object has no attribute '__name'
         #__开头的属性是隐藏属性,无法通过对象访问
p.__name = '猪八戒' # 这个设置无效,不会报错
print(p._Person__name)
p._Person__name = '沙和尚'

print(p.get_name())

方法三: 常用的

效果图三:

代码三:

# 使用__开头的属性,实际上依然可以在外部访问,所以这种方式一般不用
#  一般会将一些私有属性(不希望被外部访问的属性)以_开头
#  一般情况下,使用_开头的属性都是私有属性,没有特殊需要不要修改私有属性
class Person:
  def __init__(self,name):
    self._name = name

  def get_name(self):
    return self._name

  def set_name(self,name):
    self._name = name

p = Person('牛一')

print(p._name)

以上这篇python隐藏类中属性的3种实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

PYTHON EVAL的用法及注意事项解析

前言 eval是Python的一个内置函数,这个函数的作用是,返回传入字符串的表达式的结果。想象一下变量赋值时,将等号右边的表达式写成字符串的格式,将这个字符串作为eval的参数,eva...

Python写的创建文件夹自定义函数mkdir()

Python对文件的操作还算是方便的,只需要包含os模块进来,使用相关函数即可实现目录的创建。 主要涉及到三个函数: 1、os.path.exists(path) 判断一个目录是否存在...

利用Psyco提升Python运行速度

Psyco 是严格地在 Python 运行时进行操作的。也就是说,Python 源代码是通过 python 命令编译成字节码的,所用的方式和以前完全相同(除了为调用 Psyco 而添加的...

Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例

Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例

本文实例讲述了Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 滤镜特效,Marble Filt...

详解python发送各类邮件的主要方法

 python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点。 一、相关模块介绍 发送邮件主要用到了sm...