• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞代码 4年前 (2022-01-09) 25次浏览 已收录 0个评论

如何在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,所以你在外部使用原来的私有成员的名字时,会提示找不到。 比如:

<b>本文来源gao@dai!ma.com搞$代^码!网7</b>
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'


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python里运用私有属性和方法总结

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址