python - Python:当我覆盖它们时,基类属性和方法会发生什么?他们还“存在”吗?
问题描述
说我有
class Base:
def __init__(self):
self.x = 5
我得出
class Derived(Base):
def __init__(self):
self.x = 4
现在,我仍然想访问派生类中x
的原始内容。Base
但是我覆盖了它,所以它永远消失了吗?或者我还能在某个地方找到它吗?
请注意,我不能调用x
其他东西的派生值,因为方法Base
会调用self.x
,并且如果该方法是从 -object 调用的,则self.x
必须如此!4
Derived
上面的例子是针对一个变量的,但同样的问题也适用于 in 中的方法,在Base
中被覆盖Derived
。
解决方案
如果您在 init 之外包含属性,它将是一个类绑定参数。这样您就可以访问Base.x
因此,您创建的派生的每个实例都将具有x
根据 init 的属性,并且您可以访问Base
属性。
>>> class Base:
... x = 5
>>> class Derived(Base):
... def __init__(self):
... self.x = 4
>>> derived_instance = Derived()
>>> derived_instance.x
4
>>> Base.x
5
>>>
推荐阅读
- java - 如何在不重新启动应用程序的情况下在 PCF 中运行的 Spring Boot 应用程序中加载更改的环境变量?
- regex - 正则表达式在第一次出现时停止
- reactjs - .hasClass 在 Jest 单元测试中不起作用
- python - pandas 仅将我的数据保存到 csv 文件的一列中
- r - 根据条件估算时间
- excel - 将嵌套的 LOOKUP 公式转换为 VBA 代码
- c++ - C++ 比较字符
- node.js - 从客户端订阅 NodeJS 服务器上的长时间处理请求反馈
- python - 'register' 对象在 Django 中没有属性 'get'
- vba - 如何允许通过 Microsoft Access 中的组合框向表中添加值?