如果对象实例化没有适当的值,我需要返回 False。据我所知,使用 init 方法不可能做到这一点。是否有另一种方法可以用来检查值是否返回 bool 值?
class Test:
def __init__(self,x,y,z):
if x == 0 and y == 0 and z == 0:
return False
self.x = x
self.y = y
self.z = z
print(Test(0, 0, 0)) #should return False
最佳答案
Test(0,0,0)
是构造函数的调用,并且始终返回 Test
类的实例。尝试从 __init__
返回任何值都会导致 TypeError
。
你真正想要的是 Factory Pattern 。 TestFactory
提供了一个用于创建测试的静态方法,该方法将返回 None
,这是“无效”对象的更合理值,在您的特殊情况下,否则只是一个普通的测试。 p>
class Test:
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
class TestFactory:
@staticmethod
def create_test(x,y,z):
if x == 0 and y == 0 and z == 0:
return None
else:
return Test(x,y,z)
print(TestFactory.create_test(0,0,0))
关于python-3.x - 如果类对象的初始化在 Python 中具有不需要的值,则返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43599499/