zoukankan      html  css  js  c++  java
  • Python 面向对象3-成员修饰符

    1.私有的普通字段

    
    
    class Foo:

    def __init__(self,name):
    self.__name = name

    def show(self):
    print (self.__name)


    obj = Foo('Alex')
    print (obj.__name)
    # obj.show()

    现在我们在name之前添加两个__,字段变成私有的,此刻我们单独运行obj.__name,报错

    AttributeError: 'Foo' object has no attribute '__name'

    这是因为私有的字段只能在类里面访问,此刻我们单独运行obj.show()是OK的。

    2.私有的静态字段:

      我们定义了一个类Foo,定义了一个私有的静态字段__cc,如果直接在外面用Foo.__cc来访问的话会报“没有属性”的错误,但是通过实例化一个对象,我们可以通过方法f2()来访问私有的静态字段。

    class Foo:
    
        __cc = 123
    
        def __init__(self,name):
            self.__name = name
    
        def f1(self):
            print (self.__name)
            # print ("HELLO")
    
        def f2(self):
            print (Foo.__cc)
            print (self.__cc)
    obj = Foo('Alex')
    obj.f2()

    结果:
      123
      123

    如果我们不想通过对象来访问,需要通过类来访问的话,代码可以更改成下面的样子:

    class Foo:
    
        __cc = 123
    
        def __init__(self,name):
            self.__name = name
    
        def f1(self):
            print (self.__name)
            # print ("HELLO")
    
        @staticmethod
        def f2():
            print (Foo.__cc)
    Foo.f2()
    结果:
      123

    对于继承关系而言,如果不是私有普通变量,那么在子类中是可以访问的:

    class Foo:
    
        __cc = 123
    
        def __init__(self,name):
            self.name = name
    
        def f1(self):
            print (self.name)
            # print ("HELLO")
    
        @staticmethod
        def f2():
            print (Foo.__cc)
    
    class Bar(Foo):
    
        def f3(self):
            print (self.name)
    
    obj = Bar("Alex")
    obj.f3()
    print (Bar.cc)
    结果:
      Alex
      123

    如果改成私有变量,那么执行程序报错

    AttributeError: 'Bar' object has no attribute '_Bar__name'

    3.私有的普通方法:

      只能在类内部调用

  • 相关阅读:
    js小案例---1.随机10不重复10数并排序2.一次输入10数并输出和
    23种设计模式-----转载
    类与类之间的关系-----转载
    设计模式六大原则-----转载
    配置JDK时环境变量path和JAVA_HOME的作用是什么?
    安装和配置JDK,并给出安装、配置JDK的步骤。
    1.Java为什么能跨平台运行?请简述原理。
    求圆的周长和面积
    java第一节课
    相关元素操作
  • 原文地址:https://www.cnblogs.com/python-study/p/5735148.html
Copyright © 2011-2022 走看看