class and private variables

后端 未结 3 1809
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 04:03
class Test1:
    def __init__( self ):
        self.__test = 1
    def getvalue( self ):
        return self.__test

class Test2( Test1 ):
    def __init__( self ):
        T         


        
3条回答
  •  生来不讨喜
    2021-01-27 04:24

    In Python, private member __bar of class Foo will be automatically renamed to _Foo__bar, so the __test in Test1 is _Test1__test and that in Test2 is _Test2__test. The two members are actually different. This is by design, to "avoid name clashes of names with names defined by subclasses".

    Use a single underscore _test if you want the subclass to see the variable while still want to keep it not part of the public interface.

提交回复
热议问题