[英]Checking in parent class if children different arguments (different number of arguments) are negative?
Let's suppose we have this parent class: 假设我们有这个父类:
class Parent:
def __init__(self):
pass
And these two children: 这两个孩子:
class Child1(Parent):
def __init__(self, 1stparam):
pass
class Child2(Parent):
def __init__(self, 1stparam, 2ndparam):
pass
I would like a method for class Parent
to check if the arguments passed are negative. 我想要让Parent
类检查传入的参数是否为负的方法。 For example: 例如:
class Parent:
def __init__(self):
pass
def check_data( allparameters ):
if allparameters <0:
return false
I would like to check_data
for all childs by inheriting this method, for example: 我想通过继承此方法来check_data
所有子项的数据,例如:
mychild1 child1(-1)
mychild2 child2(1, -1)
[mychild1.check_data(), mychild2.check_data()]
This should return, of course, [False, False]
. 当然,应该返回[False, False]
。
You need function with *args
. 您需要使用*args
函数。 Sample example: 示例示例:
def check_negative(*args):
for item in args:
if item < 0:
return False
else:
return True
Sample run: 样品运行:
>>> check_negative(1)
True
>>> check_negative(-1)
False
>>> check_negative(1, 1)
True
>>> check_negative(1, -1)
False
>>> check_negative(-1, -1)
False
For more details, read: What do *args and **kwargs mean? 有关更多详细信息,请阅读: * args和** kwargs是什么意思?
You could do something like this: 您可以执行以下操作:
class Parent(object):
def __init__(self):
self.data = []
def check_data(self):
return all(map(lambda arg: arg >= 0, self.data))
class Child1(Parent):
def __init__(self, param_1):
self.data = [param_1]
class Child2(Parent):
def __init__(self, param_1, param_2):
self.data = [param_1, param_2]
print(Child1(1).check_data()) # True
print(Child1(-1).check_data()) # False
print(Child2(1, 1).check_data()) # True
print(Child2(1, -1).check_data()) # False
print(Child2(-1, 1).check_data()) # False
print(Child2(-1, -1).check_data()) # False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.