Python中的“Self”对象是什么?

我不理解以下
Python代码中的“Self”对象:

>>> class Ancestor( object ):
    def __init__( self ):
        self.name = "Ancestor"
    def getName( self ):
        return self.name


>>> class Base1( Ancestor ):
    def __init__( self ):
        self.name = "Base1"
        super( Base1, self ).__init__( )
    def getName( self ):
        return self.name


>>> class Base2( Base1 ):
    def __init__( self ):
        self.name = "Base2"
        super( Base2, self ).__init__( )
    def getName( self ):
        return self.name
    def getB1Name( self ):
        return super( Base2, self ).getName( )


>>> b2 = Base2( )
>>> b2.getName( )
'Ancestor'
>>> b2.getB1Name( )
'Ancestor'

我无法理解结果.我期待b2.getName()的结果为“Base2”,b2.getB1Name()的结果为“Base1”

最佳答案 self指的是实例,而不是类.您只有一个实例,因此self的所有用法都指向同一个对象.在Base2 .__ init__中,您在此对象上设置了一个名称.然后调用super,它调用Base1 .__ init__,它在同一个对象上设置一个新名称,覆盖旧的名称.

如果你真的需要,你可以使用double-underscore attributes来实现你想要的.

点赞