xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Python data hiding All In One

Python data hiding All In One

private data / private method

⚠️ 约定:class 里面使用单个下划线,表示私有的属性私有的方法,实际上在 class 外面是可以访问

def _private_method():
  self._private_data = ""

Strongly private methods and attributes have a double underscore at the beginning of their names.
This causes their names to be mangled, which means that they can't be accessed from outside the class.


class Spam:
  __egg = 7
  def print_egg(self):
    print(self.__egg)

s = Spam()
s.print_egg()
# instance._Class__attribute 🚀
print("✅ s._Spam__egg =", s._Spam__egg)
# print("❓ s._Spam =", s._Spam)
# ❌ AttributeError: 'Spam' object has no attribute '_Spam'
print(s.__egg)


"""
$ py3 ./data-hiding-strong-private.py

7
✅ s._Spam__egg = 7
Traceback (most recent call last):
  File "/Users/xgqfrms-mm/Documents/github/Python-3.x-All-In-One/src/./data-hiding-strong-private.py", line 9, in <module>
    print(s.__egg)
AttributeError: 'Spam' object has no attribute '__egg'
"""

demos


class Queue:
  def __init__(self, contents):
    self._hidden_list = list(contents)

  def push(self, value):
    self._hidden_list.insert(0, value)

  def pop(self):
    return self._hidden_list.pop(-1)

  def __repr__(self):
    return "Queue({})".format(self._hidden_list)

queue = Queue([1, 2, 3])
print(queue)
queue.push(0)
print(queue)
queue.pop()
print(queue)
print(queue._hidden_list)


"""

$ py3 ./data-hiding-queue.py

Queue([1, 2, 3])
Queue([0, 1, 2, 3])
Queue([0, 1, 2])
[0, 1, 2]
"""


class Spam:
  __egg = 7
  def print_egg(self):
    print(self.__egg)

s = Spam()
s.print_egg()
# instance._Class__attribute 🚀
print("✅ s._Spam__egg =", s._Spam__egg)

# 如何访问 python class 的属性
print("✅ Spam._Spam__egg =", Spam._Spam__egg)
# print("❓ s._Spam =", s._Spam)
# ❌ AttributeError: 'Spam' object has no attribute '_Spam'

# print(s.__egg)

"""
$ py3 ./data-hiding-strong-private.py

7
✅ s._Spam__egg = 7
✅ Spam._Spam__egg = 7
Traceback (most recent call last):
  File "/Users/xgqfrms-mm/Documents/github/Python-3.x-All-In-One/src/./data-hiding-strong-private.py", line 9, in <module>
    print(s.__egg)
AttributeError: 'Spam' object has no attribute '__egg'
"""


image

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://www.cnblogs.com/xgqfrms/p/17565339.html



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-07-26 23:59  xgqfrms  阅读(5)  评论(2编辑  收藏  举报