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

为什么我不能在Python中访问超类的私有变量?

发布时间:2020-12-16 22:03:59 所属栏目:Python 来源:网络整理
导读:我知道我应该使用访问方法.我在datetime模块中看到类datetime继承自date. class datetime(date): 我还看到datetime能够访问日期成员,如__repr__: def __repr__(self): """Convert to formal string,for repr().""" L = [self._year,self._month,self._day,#

我知道我应该使用访问方法.我在datetime模块中看到类datetime继承自date.

class datetime(date):
    

我还看到datetime能够访问日期成员,如__repr__:

def __repr__(self):
    """Convert to formal string,for repr()."""
    L = [self._year,self._month,self._day,# These are never zero
         self._hour,self._minute,self._second,self._microsecond]

我试图将datetime子类化为其添加一些信息,然后编写一个类似的__repr__函数:

def __repr__(self):
    """Convert to formal string,self._microsecond,self._latitude,self._longitude]

调试器抱怨self._year不存在. (然而,自己的作品.)

我知道我应该使用访问功能.我只想了解为什么datetime能够访问date的私有变量但我的子类不能.

最佳答案
如果你看一下end of datetime.py,你会看到:

try:
    from _datetime import *
except ImportError:
    pass

这会导入以前定义的python类的C版本,因此将使用它们,而那些没有您尝试访问的成员.

(编辑:李大同)

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

    推荐文章
      热点阅读