首页 > 解决方案 > 从父类函数继承属性而不执行父类函数的其余部分

问题描述

我只想从类 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

...无需更改我的代码(无需删除我在第一类中的打印功能)。

标签: pythonclassinheritance

解决方案


正如 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()

推荐阅读