继承和基类方法调用python

时间:2011-10-20 20:24:26

标签: python inheritance

我希望基类中的方法可以在同一个类中调用另一个方法,而不是在继承的类中调用覆盖方法。 我希望以下代码打印出来

B班:6

A类:9

可以这样做吗?


# Base class definition
class ClassA(object):
    def __init__(self):
        print("Initializing A")

    # hoping that this function is called by this class's printFnX
    def fnX(self, x):
        return x**2

    def printFnX(self, x):
        print("ClassA:",self.fnX(x))

# Inherits from ClassA above
class ClassB(ClassA):
    def __init__(self):
        print("initizlizing B")

    def fnX(self, x):
        return 2*x

    def printFnX(self, x):
        print("ClassB:", self.fnX(x))
        ClassA.printFnX(self,x)

bx = ClassB()
bx.printFnX(3)

2 个答案:

答案 0 :(得分:49)

恭喜,您已经发现Python的双下划线名称修改的激励用例: - )

有关详细信息和已完成的示例,请参阅:http://docs.python.org/tutorial/classes.html#private-variableshttp://docs.python.org/reference/expressions.html#atom-identifiers

以下是如何将它用于您的示例:

# Base class definition
class ClassA(object):
    def __init__(self):
        print("Initializing A")

    # hoping that this function is called by this class's printFnX
    def fnX(self, x):
        return x**2
    __fnX = fnX

    def printFnX(self, x):
        print("ClassA:",self.__fnX(x))

# Inherits from ClassA above
class ClassB(ClassA):
    def __init__(self):
        print("initizlizing B")

    def fnX(self, x):
        return 2*x

    def printFnX(self, x):
        print("ClassB:", self.fnX(x))
        ClassA.printFnX(self,x)

bx = ClassB()
bx.printFnX(3)

用例被描述为在Open-Closed Principle找到的“子类化艺术”中实现http://www.youtube.com/watch?v=yrboy25WKGo&noredirect=1的一种方式。

答案 1 :(得分:-4)

同样可以通过fnXprintFnX这两种类方法来实现。

class ClassA(object):

    def __init__(self):
        print("Initializing A")

    # hoping that this function is called by this class's printFnX
    @classmethod
    def fnX(self, x):
        return x ** 2

    @classmethod
    def printFnX(self, x):
        print("ClassA:",self.fnX(x))

class ClassB(ClassA):
    def __init__(self):
        print("initizlizing B")

    def fnX(self, x):
        return 2*x

    def printFnX(self, x):
        print("ClassB:", self.fnX(x))
        ClassA.printFnX(x)


bx = ClassB()<br>
bx.printFnX(3)