以这种方式使用自动调用__init__是否安全? [英] Is it safe to use autocall __init__ in this way?
问题描述
我想强迫孩子打电话给父级构造函数,并找到了此答案,看起来很不错.但是,我不确定我在做什么是否安全.我有这个:
I wanted to force children to call parent constructor and found this answer which seems to do the job fine. However, I'm a bit unsure if what I'm doing is safe. I have this:
# Copied from answer linked above
class meta(type):
def __init__(cls,name,bases,dct):
def auto__call__init__(self, *a, **kw):
for base in cls.__bases__:
base.__init__(self, *a, **kw)
cls.__init__child_(self, *a, **kw)
cls.__init__child_ = cls.__init__
cls.__init__ = auto__call__init__
# My code
import unittest
class TestBase(unittest.TestCase, metaclass=meta):
def __init__(self):
self.testvar="Hello, World!"
class A(TestBase):
def foo(self):
# Inherited from TestBase
print(self.testvar)
# Inherited from unittest.TestCase
self.assertEqual("Hello, World!", self.testvar)
A().foo()
这将打印"Hello,World!"(您好,世界!);正如预期的那样,我可以使用unittest.TestCase
中的assertEqual
,但是我感觉自己可能在这里遇到了麻烦.这样安全吗?它可以与unittest
发生任何碰撞吗?
This prints "Hello, World!" as expected, and I'm able to use assertEqual
from unittest.TestCase
, but I have a feeling that I might be on very thin ice here. Is this safe to do? Can it collide with unittest
in any way?
在原始帖子中,TestBase
并非从unittest.TestCase
继承.就是这样.
In the original post, TestBase
did not inherit from unittest.TestCase
. That's the difference.
推荐答案
无论如何都没有任何反应,如果您实际覆盖了该方法,则只需要委托给父对象即可;如果没有,则原始方法不会被遮盖并且会正常调用.
Here nothing's happening anyway, you only need to delegate back to the parent if you actually override the method, if you don't then the original method is not shadowed and will be called normally.
我强烈建议您不要这样做,尤其是对于单元测试,因为__init__
实际上并没有任何用处:unittest
仅根据其发现的方法名称(初始化)调用__init__
来初始化测试用例.您想要的钩子是setUp
(和tearDown
,尽管addCleanup
通常更安全,更可靠).您可以在测试类中定义帮助方法,但是您应该不自己实例化测试用例.
I'd strongly recommend not doing this though, especially for unittest as __init__
is not actually of any use there: unittest
only calls __init__
to initialise test cases based on the method names it finds, the initialisation hook you want is setUp
(and tearDown
though addCleanup
is usually safer and more reliable). You can define helper methods in test classes, but you should not instantiate testcases yourself.
Plus unittest
并不是很好,它很冗长,API面很大,并且基于类的设计妨碍了模块化(也许有些出乎意料).我强烈建议您在pytest
找个雄鹿.
Plus unittest
is not great, it's quite verbose, the API surface is large, and the class-based design hampers the modularity (somewhat unexpectedly maybe). I'd strongly recommend taking a gander at pytest
.
这篇关于以这种方式使用自动调用__init__是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!