从基类调用函数

时间:2017-04-24 16:14:12

标签: python python-2.7 oop

我是Python的新手。

我有一个类,它有一些常用的定义,可以在模块中的其他几个类中使用。这是我程序的当前结构。

 class A(object):

    def __init__(self, x, y):
        """Initialization method"""
        super(A, self).__init__()
        self.x = x
        self.y = y

    def function_1(self, ftype):
        <<<some steps>>>
        return abc

    def function_2(self, stype):
        <<<some steps>>>        
        return xyz

class B(A):
    def __init__(self, x, y, e_type):
        A.__init__(self, x, y)
        self.e_type = enablement_type

    def function_3(self, mtype):
        <<<some steps>>>
        **HERE I need to call the function1 and function2 of class A**

1:只需将基类中的函数调用为

   A.function1(self, ftype='new')
   A.function2(self, stype='new')

是正确的方法吗?当我这样做时,Pylint说好。

2:另外,你能用简单的术语详细说明吗

2 个答案:

答案 0 :(得分:1)

第一个问题: 你正在做的是具有继承概念的代码可重用性。

一旦你说了B类(A)&#39;,A的所有成员和功能都可以在B中使用。因此,你可以像下面那样直接调用B函数

self.function1(ftype='new')
self.function2(stype='new')

这是在Python中访问实例的任何函数的典型方法。 无论你提到的是什么,只需访问任何其他文件中的静态函数。这无论如何都会起作用。但它与继承无关。

第二个问题: 在继承的情况下,您可以选择从基类中完全重新定义通用可重用函数,或者为特殊情况扩展某些功能,或者只是按原样使用。 在扩展现有函数的情况下,您需要做的是覆盖您想要扩展的函数,它的主体应该调用所有基类函数,然后调用其他代码。这里使用super.function()

来调用基类函数
def function1(self, ftype):
    super.function1(self, ftype)
    # the new code specific to this class goes here

init ()是特殊函数,称为构造函数。在实例化类时调用类似于&#39; objInstance = B()&#39; 。其他功能如上所述进行处理。

希望它澄清你的怀疑。

答案 1 :(得分:0)

通常,您可以调用这样的继承函数:

self.function1('new')
self.function2('new')

您编写的内容可行,但需要您确定包含这些方法的确切基类。这是一个复杂的问题,并且可能通过让继承完成工作来轻松避免错误。

相关问题