python类中方法加单下划线、双下划线、前后双下滑线的区别

首先看一段代码:

class Foo():
    def __init__(self):
        print "__init__ method"

    def public_method(self):
        print "public_method"

    def __private_method(self):
        print "__private_method"

    def _halfprivate_method(self):
        print "_halfprivate_method"

这里我们定义了一个类Foo,类成员函数有双下划线方法__private_method和单下滑线方法_halfprivate_method,调用public_method和_halfprivate_method结果如下:

f = Foo()
f.public_method()
f._halfprivate_method()

结果:
__init__ method
public_method
_halfprivate_method

显示没有问题。调用__private_method结果如下:

f = Foo()
f.__private_method()

结果:
Traceback (most recent call last):
__init__ method
  File "C:/Python_Data_Analyse1/python下划线的意义.py", line 19, in <module>
    f.__private_method()
AttributeError: Foo instance has no attribute '__private_method'

结果显示Foo的实例化的对象没有属性__private_method,但是如果使用_类__object的方式,就可以访问私有方法了,如下:

f = Foo()
f._Foo__private_method()

结论:python 的类实例化的对象可以调用单下划线开头的方法,不能调用双下划线的方法;

再看一段代码:

class A(object):
    def __init__(self):
        self.__private()
        self.public()

    def __private(self):
        print 'A.__private()'

    def public(self):
        print 'A.public()'

class B(A):
    def __private(self):
        print 'B.__private()'

    def public(self):
        print 'B.public()'
b = B()

显示结果为:

__init__ method
A.__private()
B.public()

实例化子类B就会执行__init__方法,调用静态方法__private,但是静态方法不会被子类继承,所以依然执行A中的__private方法,而public为普通方法,可以被B继承,所以会被B中相同的方法名的方法重写;

所以如果我们想要让父类的方法不被子类重写,或者继承,可以将父类的方法定义为私有方法;

延伸:如果想要父类的方法必须被子类重写呢?如何实现?

class A(object):

    def test(self):
        raise NotImplementedError

class B(A):

    def test(self):
        print "the method come true"

b = B()
b.test()

也就是说,如果子类不实现父类的test()方法,就会触发NotImplementedError错误;

最后总结:前后双下滑线是python语法中class的内置方法;前面双下滑线是表示私有属性或者方法;前面单下划线表示该成员不希望被子类继承/调用,但是实际上是可以被继承或者调用的,这个只是python程序的一般约定,如果有字段或者方法不希望被调用,可以这么搞;

参考:https://my.oschina.net/chinesezhx/blog/729803

       http://www.cnblogs.com/hester/articles/4936603.html

原文地址:https://www.cnblogs.com/cqq-20151202/p/6591573.html