Python 继承-在方法中调用方法

Python 继承-在方法中调用方法,python,python-3.x,Python,Python 3.x,我知道super()函数允许您从子类调用父方法。所以在这个例子中: class Exam(): def __init__(self, a): self.a = a def show(self): print("This is from parent method") class Quiz(Exam): def __init__(self, b, a): super().__init_

我知道
super()
函数允许您从子类调用父方法。所以在这个例子中:

class Exam():
    def __init__(self, a):
        self.a = a
        
    def show(self):
        print("This is from parent method")


class Quiz(Exam):
    def __init__(self, b, a):
        super().__init__(a)
        self.b = b
        
    def show(self):
        print("This is from child method")
        super().show()

q = Quiz('b', 'a')
q.show()

>>> 'This is from child method'
>>> 'This is from parent method'
   
如果我在父类和子类中都添加了另一个名为
get_score
的方法,会怎么样

class Exam():
    def __init__(self, a):
        self.a = a
        
    def show(self):
        print("This is from parent method")
        print (self.get_score())
    
    def get_score(self):
        return self.a
    
    
class Quiz(Exam):
    def __init__(self, b, a):
        super().__init__(a)
        self.b = b
        
    def show(self):
        print("This is from child method")
        super().show()
        print (self.get_score())
    
    def get_score(self):
        return self.b

q = Quiz('b', 'a')
q.show()

>>> 'This is from child method'
>>> 'This is from parent method'
>>> 'b'
>>> 'b'
我可以理解为什么在子类中调用
super().show()
会返回
'b'
,因为我正在覆盖
get\u score()
方法

但是,有没有一种方法可以维护父类的完整性,以便在调用
super().show()时

我得到这个了吗

>>> 'This is from child method'
>>> 'This is from parent method'
>>> 'a'
>>> 'b'

如果这是糟糕的设计,请提前道歉。让我知道我可以采取哪些其他选择,即使这意味着我应该使用方法的名称来避免这种冲突。

使用名称混乱,这将防止子类中的名称冲突 :


谢谢你的回答。我想让你提出一个建议,关于是否将名称弄脏视为一种良好的做法?或者还有其他方法可以解决同样的问题吗?@AnuragReddy它存在的唯一目的是防止子类中的名称冲突。另一种方法是为方法使用另一个名称(这本质上就是名称mangling所做的)。您正在重写该方法,不能同时使用它。从这个玩具的例子中,很难说这是不是坏的。谢谢你的回复。现在我很清楚了。我想我可以直接调用
super().get_score()
,得到同样的结果,但我想混淆一些技术细节,让用户只使用一种方法来完成大部分繁重的工作。谢谢你,这很有效。我选择了你的答案作为最佳答案@胡安帕·阿里维拉加
class Exam():
    def __init__(self, a):
        self.a = a

    def show(self):
        print("This is from parent method")
        print (self.__get_score())

    def __get_score(self):
        return self.a

    get_score = __get_score


class Quiz(Exam):
    def __init__(self, b, a):
        super().__init__(a)
        self.b = b

    def show(self):
        print("This is from child method")
        super().show()
        print (self.__get_score())

    def __get_score(self):
        return self.b

    get_score = __get_score


q = Quiz('b', 'a')
q.show()