加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:29:56 所属栏目:Python 来源:网络整理
导读:我不理解以下 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 )._
我不理解以下 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来实现你想要的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读