zoukankan      html  css  js  c++  java
  • Python面向对象中的“私有化”

    Python面向对象中的“私有化”

    Python并不直接支持私有方式,而要靠程序员自己把握在外部进行特性修改的时机。

    为了让方法或者特性变为私有(从外部无法访问),只要在它的名字前面加上双下划线即可。

    由双下划线 __ 开始的属性在运行时被“混淆”,所以直接访问是不允许的。

    实际上,在 Python 带有双下划线的属性或方法并非正真意义上的私有,它们仍然可以被访问。

    在类的内部定义中,所有以双下划线开始的名字都被“翻译”成前面加上单下划线和类名的形式。

    示例:

    >>> class TestObj(object):
    ...     __war = "world"
    ...     
    ...     def __init__(self):
    ...         self.__har = "hello"
    ...         
    ...     def __foo(self):
    ...         print(self.__har + self.__war)
    ...         
    ...     
    ...
    >>> t = TestObj()
    
    >>> dir(t) # 拿到t里面的所有方法
    ['_TestObj__foo', '_TestObj__har', '_TestObj__war', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getat
    tribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__
    ', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
    
    >>> t.__war
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
        t.__war
    AttributeError: 'TestObj' object has no attribute '__war'
    
    >>> t.__har
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
        t.__har
    AttributeError: 'TestObj' object has no attribute '__har'
    
    >>> t.foo()
    Traceback (most recent call last):
      File "<input>", line 1, in <module>
        t.foo()
    AttributeError: 'TestObj' object has no attribute 'foo'
    
    >>> t._TestObj__war
    'world'
    
    >>> t._TestObj__har
    'hello'
    
    >>> t._TestObj__foo()
    helloworld
  • 相关阅读:
    CSP2021&NOIP2021游记
    P3835[模板]可持久化平衡树【无旋Treap】
    P4688[Ynoi2016]掉进兔子洞【莫队,bitset】
    C# (CSharp) ADODB.Command示例
    求最大公约数 算法记录
    流逝时间+Windows下监测文件夹
    C# WinForm开发系列 文章索引
    09年搞笑签名
    高三班主任写给学生的一封信(在读大学的要看完)
    北京生存法则
  • 原文地址:https://www.cnblogs.com/bigtreei/p/9029528.html
Copyright © 2011-2022 走看看