Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python父/子类方法调用_Python - Fatal编程技术网

Python父/子类方法调用

Python父/子类方法调用,python,Python,Linux上的Python 2.7.6 我正在使用一个从父级继承的测试类。父类包含许多子类所共有的字段,我需要调用parentsetUp方法来初始化这些字段。调用ParentClass.setUp(self)是正确的方法吗?下面是一个简单的例子: class RESTTest(unittest.TestCase): def setUp(self): self.host = host self.port = port self.protoco

Linux上的Python 2.7.6

我正在使用一个从父级继承的测试类。父类包含许多子类所共有的字段,我需要调用parent
setUp
方法来初始化这些字段。调用
ParentClass.setUp(self)
是正确的方法吗?下面是一个简单的例子:

class RESTTest(unittest.TestCase):
    def setUp(self):
        self.host = host
        self.port = port
        self.protocol = protocol
        self.context = context

class HistoryTest(RESTTest):
    def setUp(self):
        RESTTest.setUp(self)
        self.endpoint = history_endpoint
        self.url = "%s://%s:%s/%s/%s" %(self.protocol, self.host, self.port, self.context, self.endpoint)

    def testMe(self):
        self.assertTrue(True)

if __name__ == '__main__':
    unittest.main()

这是正确的吗?这似乎有效。

你可以使用
super
来实现这一点

super(ChildClass, self).method(args)

class HistoryTest(RESTTest):
    def setUp(self):
        super(HistoryTest, self).method(args)
        ...
在Python 3中,您可以编写:

class HistoryTest(RESTTest):
    def setUp(self):
        super().method(args)
        ...
这更简单

见:

super()
可以避免显式引用基类,这很好。但主要的优势在于多重继承,在这里可以发生各种各样的继承。如果还没有,请查看

多重继承 要(尝试)回答您评论中的问题:

如何指定要调用的超级方法

从我对多重继承(Python)哲学的理解来看,您没有。我的意思是,
super
,以及方法解析顺序(MRO),应该正确地做事情,并选择合适的方法。(Yes方法是复数形式,见下文。)

有很多博客帖子/所以你可以通过关键词“多重继承”、“钻石”、“MRO”、“超级”等找到关于这一点的答案。提供了一个Python 3示例,我觉得很惊讶,但在其他来源中没有找到:

class A:
    def m(self):
        print("m of A called")

class B(A):
    def m(self):
        print("m of B called")
        super().m()

class C(A):
    def m(self):
        print("m of C called")
        super().m()

class D(B,C):
    def m(self):
        print("m of D called")
        super().m()

D().m()

m of D called
m of B called
m of C called
m of A called
看到了吗?由于
super
,调用了
B.m()
C.m()
,考虑到D继承自
B
C
,这似乎是正确的做法

我建议你像我刚才那样玩这个例子。添加一些
print
s,您将看到,在调用
D().m()
时,类
B
中的
super().m()
语句本身调用
C.m()
。当然,如果调用
B().m()
B
实例,而不是
D
实例),则只调用
A.m()
。换句话说,
B
中的
super()


使用
super
everywhere听起来像银弹,但您需要确保继承模式中的所有类都是协作的(另一个要挖掘的关键字),并且不要断开链,例如在子类中需要额外的参数时。

您使用的python版本是什么?好的,那么多重继承呢?如何指定要调用哪个super
方法
super()
调用直接父类,如果函数不存在,它将向上搜索链。因此,如果您有
类Obj(A,B,C):
,则
super()
调用将首先在A中查找,如果不在那里,则在B中查找,依此类推。