简体   繁体   English

在父类中检查子级不同的参数(不同数量的参数)是否为负?

[英]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
  • The map function applies a function on each element of an iterable an returns the results in a iterable. map函数在iterable的每个元素上应用一个函数,并以iterable返回结果。
  • The lambda function returns False when provided with a negative number. 当提供负数时,lambda函数将返回False。
  • The all function returns True if all elements in the given list are True. 如果给定列表中的所有元素均为True,则all函数将返回True。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM