python里运用私有属性和方法总结

yipeiwu_com6年前Python基础

如何在PYTHON里运用私有属性和方法

class File:

  def __init__(self, name):

    self.name = name

    self.code = "ABCDEF"

    

file_A = File("file_A")

#假设我们有一个类,叫做文件类,设置一个对象file_A。

file_A.code

#如果直接调用属性,是可以看到属性里面有什么,但是如果这是个机密的密码不能公布,是不能这么处理的。

class File:

  def __init__(self, name):

    self.name = name

    self.__code = "ABCDEF"

    

file_A = File("file_A")

print(file_A.code)

#如果不想密码公布,可以对属性的名称加上__,但是这里出错了。

class File:

  def __init__(self, name):

    self.name = name

    self.__code = "ABCDEF"

    

file_A = File("file_A")

print(file_A.__code)

#很多人以为是因为外部的名称打少了__,但是这里依旧出错了,那是因为这是私有的属性。

class File:

  def __init__(self, name):

    self.name = name

    self.__code = "ABCDEF"

  def open(self):

    print("This is the AAA file!")

    

file_A = File("file_A")

file_A.open()

#除了属性,方法也能私有吗?答案是可以的。

class File:

  def __init__(self, name):

    self.name = name

    self.__code = "ABCDEF"

  def __open(self):

    print("This is the AAA file!")

    

file_A = File("file_A")

file_A.__open()

#私有方法以后,看出来和私有属性的返回结果是一致的。

class File:

  def __init__(self, name):

    self.name = name

    self.__code = "ABCDEF"

  def __open(self):

    print("This is the AAA file!")

    

file_A = File("file_A")

print(file_A._File__code)

file_A._File__open()

#在PYTHON里面如果在方法和属性那里加上_类名是可以看到私有的属性和方法的。

知识点扩展:

python默认的成员函数和成员变量都是公开的,python 私有属性和方法没有类似别的语言的public,private等关键词来修饰。 在python中定义私有变量只需要在变量名或函数名前加上 "__"两个下划线,那么这个函数或变量就会为私有的了。 在内部,python使用一种 name mangling 技术,将 __membername替换成 _classname__membername,所以你在外部使用原来的私有成员的名字时,会提示找不到。 比如:

class Person:

def __init__(self):
self.__name = 'haha'#私有属性
self.age = 22

def __get_name(self):##私有方法
return self.__name

def get_age(self):
return self.age

person = Person()
print person.get_age()
print person.__get_name()
运行结果是:22 Traceback (most recent call last): File "E:\pythoner\zenghe\jay.py", line 38, in print person.__get_name() AttributeError: Person instance has no attribute '__get_name'

我们这里定义的__name是私有属性,__get_name()是私有方法。如果直接访问的话,会提示找不到相关的属性或者方法,但是如果你真要访问私 有的相关数据的话, 也是可以访问的,严格地说,私有方法在它们的类外是可以访问的,只是不容易 处理。在 Python 中没有什么是真正私有的;在内部,私有方法和属性的名字被忽然改变和恢复,以致于使得它们看上去用它们给定的名字是无法使用的

相关文章

python3.6+django2.0+mysql搭建网站过程详解

python3.6+django2.0+mysql搭建网站过程详解

之前用过python2.7版本,改用3.6版本发现很多语法发生了变化。 在templates里新建一个html文件,命名为index.html作为要测试的界面, 新建一个应用,Tools...

Python win32com 操作Exce的l简单方法(必看)

实例如下: from win32com.client import Dispatch import win32com.client class easyExcel:...

Python打开文件,将list、numpy数组内容写入txt文件中的方法

python保存numpy数据: numpy.savetxt("result.txt", numpy_data); 保存list数据: file=open('data.txt'...

python利用拉链法实现字典方法示例

python利用拉链法实现字典方法示例

前言 字典也叫散列表,最大的特点是通过key来查找其对应的值其时间复杂度是O(1),下面这篇文章就来给大家介绍介绍python利用拉链法实现字典的方法。 在Python中怎样用列表实现字...

Pandas探索之高性能函数eval和query解析

Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据...