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.私有的普通方法:

  只能在类内部调用

原文地址:https://www.cnblogs.com/python-study/p/5735148.html