python - 从父类函数继承属性而不执行父类函数的其余部分
问题描述
我只想从类 2 执行打印功能,而我只想从类 1 继承属性 self.name 而不打印它的功能。是否可以仅输出为“Test John”而不在此之前仅打印“John”?
这是代码:
class One:
def __init__(self):
self.name = 'John'
print(self.name)
class Two(One):
def __init__(self):
super().__init__()
print('Test ' + self.name)
two = Two()
这是输出:
John
Test John
我想有这样的输出(只是第二行):
Test John
...无需更改我的代码(无需删除我在第一类中的打印功能)。
解决方案
正如 Konrad Rudolph 和 chepner 所说,在构造函数中执行 io 是不好的做法,但如果您真的需要这样做:您可以在类 One 的构造函数中添加类型测试,这样只有当您直接 John
初始化 One 对象时才会被打印:
class One:
def __init__(self):
self.name = 'John'
if type(self)==One:
print(self.name)
class Two(One):
def __init__(self):
super().__init__()
print('Test ' + self.name)
two = Two()
推荐阅读
- typescript - 为度量 CDK 创建数学表达式
- python - 有没有办法在使用谷歌云功能时在 /tmp 中创建一个文件夹?
- docker - 集群在不同机器上运行的 vernemq docker 容器
- xamarin.forms - 推送/弹出页面时使用屏幕阅读器读取当前页面标题
- java - Spring Boot 2.2 多模块项目自动配置 JPA 失败
- google-apps-script - 无法从电子表格中的列中获取 URL(图像 URL 保存在列中)并使用 Google App Script 中的 urlfetchapp 创建 PDF
- android - 将文本文件附加到无法在 Android 11 上运行的 Gmall 应用程序
- java - 很多时候在android中显示没有互联网连接
- node.js - 列表请求不起作用(带有 Typescript 的 Node.js 中的 Mongoose)
- django - Django“dockerized”(开发环境)中未提供静态文件