是否可以在Python中重命名方法? 像这样的东西
class Validation(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(Validation, self).__init__(methodName)
#Doesn't work
setattr(self,'do_folders_equal','test_do_folders_equal')
将方法'do_folders_equal'重命名为'test_do_folders_equal'.. 显然,上面的用法是不正确的...怎么做这个黑客?
答案 0 :(得分:3)
你不会重命名它,你只需将它分配给另一个变量:
class Validation(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(Validation, self).__init__(methodName)
self.test_do_folders_equal = self.do_folders_equal
def __init__(self, methodName='runTest'):
super(Validation, self).__init__(methodName)
self.test_do_folders_equal = self.do_folders_equal
然而,有时会有一些奇怪的相互作用与继承的方法等,所以它取决于你想要做什么。不确定这对旧式类的表现如何......
编辑:或使用在运行时读取的名称:
class Validation(unittest.TestCase):
def __init__(self, methodName='runTest'):
super(Validation, self).__init__(methodName)
setattr(self, 'test_do_folders_equal', getattr(self, 'do_folders_equal'))