zoukankan      html  css  js  c++  java
  • 面向对象的三大特征之一:封装

    封装:每个对象都包含它能进行操作所需要的所有信息,这个特性就是封装,因此对象不必依赖其他对象来完成自己的操作。这样的方法和属性包装在类中,通过类的实例来实现。

    class A:
        __x=1
    
        def __init__(self, name ,age):
            self.name = name
            self.age = age
    
        def __foo(self):
            print('from foo')
    
    print(A.__dict__)
    print('__x=',A._A__x)
    print(A.__x)
    print(A.__foo)
    
    a=A('alex',19)
    print(a.__dict__)

    结果:

    Traceback (most recent call last):
    {'__module__': '__main__', '_A__x': 1, '__init__': <function A.__init__ at 0x000000966D160488>, '_A__foo': <function A.__foo at 0x000000966D160400>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
    __x= 1
      File "C:/Users/zhang1995/PycharmProjects/untitled4/text_file/4..py", line 13, in <module>
        print(A.__x)
    AttributeError: type object 'A' has no attribute '__x'

    总结分析:从上面的代码和运行结果可以看出,prInt(A.__dict__)得出A的数据属性分别是'_A__x',函数属性是:'__init__','_A__foo'。但是A类的定义中,数据属性是__x,而函数属性则是__foo().同时,print('__x=',A._A__x)得出__x= 1。所以可以总结出python的封装并不是真正意义上的隐藏,而是在定义的时候(封装有且只能在类的定义时定义好)就已经产生了变形格式为:_所属的类名+变量名。

    这种变形的特点:

                    1.在类的外部无法直接使用,封装的属性

                     2.在类的外面无法直接使用:self.变量名

          3.子类无法覆盖父类的__开头的属性(定义的)

    封装的作用:

    一:封装数据属性:明确的区分内外,控制外部对隐藏属性的操作行为

    二:封装方法:隔离复杂度

  • 相关阅读:
    Visual Studio Code 工具使用教程
    JS获取节点的兄弟,父级,子级元素
    动态加载js
    实用的文本和图片无缝滚动效果
    兼容各种浏览器的文字循环无缝滚动效果
    中文乱码
    js 循环json
    js中获取basePath
    json转换为map
    java des 加密/解密
  • 原文地址:https://www.cnblogs.com/z18271397173/p/9130709.html
Copyright © 2011-2022 走看看