class 子类名(父类1, 父类2, ...., 父类n): pass # 通过类提供的__bases__属性可以查看到子类直接继承的所有父类,子类名.__bases__
class cartInfoTest(unittest.TestCase): # 定义一个子类cartInfoTest, 继承父类unittest.TestCase类 # 购物车的测试用例 storeID = [1, ‘北京XX‘, 11, ‘XX店‘, ‘116.316839‘, ‘39.982926‘, ‘6a84ee3d9eb72755500fe083956628d1@MS0xMTItMQ‘, ‘00dfb855c6465c81199a21672fca1f18@MTM3Mi02OTYzMg‘, ‘2‘] userInfo = ("0f776f21-4455-4342-852c-ba8d802338d3", "60E7BD2AF307BCBA39926EC51D165429CF17DDE262FAA204E701D2BAE7DF1BEF0B9AFC57D96EDE299471E2BD9F905CDE081D053C1FEF126BA9C0173F585F0B3469B30A2965B1651600679E68E610E197EF72EAFEC66D6184F1022DB5FE38B223768D1D7D029616164F05DA3128473184212D42152629DB9E3E1C800A5AD65469") def test_cart(self,): """测试name_function.py""" rootURL = cr.INTERFACE_CARTINFO headers = cr.homePageInterfaceTestHeader(self.storeID, token=self.userInfo[0], ticketName=self.userInfo[1]) param = cr.cartInfoTestParams(self.storeID) data = "param=%s" % json.dumps(param, ensure_ascii=False) r = requests.post(rootURL, headers=headers, data=data) # 调用继承的父类unittest.TestCase的方法:assertEqual self.assertEqual(‘0000‘, r.json()[‘code‘], r.json()[‘result‘]) # unittest.TestCase.assertEqual(self, 1, 2) #“基类名.方法名()” if __name__ == ‘__main__‘: unittest.main()
调用父类方法方式:
继承实现方法:
class Father: def hobby(self): print(f"{Father.__name__} love to play video game.") def cook(self): print(f"{Father.__name__} love to cook anything.") class Mother: def cook(self): print(f"{Mother.__name__} love to cook anything.") def hobby(self): print(f"{Mother.__name__} love to play video game.") class Son(Father, Mother): pass if __name__ == ‘__main__‘: son = Son() son.cook() son.hobby() # 执行结果: Father love to cook anything. Father love to play video game. #更换下继承顺序 class Son(Mother, Father): pass if __name__ == ‘__main__‘: son = Son() son.cook() son.hobby() #执行结果 Mother love to cook anything. Mother love to play video game.
父类定义了__init__方法,子类必须显式调用父类的__init__方法。
class CheckPoint(unittest.TestCase): def __init__(self, methodName=‘runTest‘): # 方法一:经典类写法,需要把父类的拿过来, 把父类执行一遍 #unittest.TestCase.__init__(self, methodName) """方法二:super的作用Man继承父类的构造函数, 优点1:父类名称改变后,此处不用同步修改, 优点2:多继承时,不用每个都写一遍""" #super(CheckPoint, self).__init__(methodName) #第三种写法(推荐):Python3的写法,与第二种等价 super().__init__(methodName) self._testMethodName = methodName self._flag = 0 self.msg = [] # 基本的布尔断言:要么正确,要么错误的验证 def checkAssertEqual(self, arg1, arg2, msg=None): """ 验证arg1=arg2,不等则fail""" try: self.assertEqual(arg1, arg2, msg) except Exception as e: self._flag += 1 self.msg.append("{}".format(msg)) print(e)
# 方法一:经典类写法,需要把父类的拿过来, 把父类执行一遍:父类名.__init__(self,父类参数)
# 方法二:super(子类名, self).__init__(methodName)
#第三种写法(推荐):Python3的写法,与第二种等价:super().__init__(methodName)
原文:https://www.cnblogs.com/dy99/p/14800167.html