-1

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. 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:

mychild1 child1(-1)
mychild2 child2(1, -1)
[mychild1.check_data(), mychild2.check_data()]

This should return, of course, [False, False].

D1X
  • 5,025
  • 5
  • 21
  • 36

2 Answers2

1

You need function with *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?

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • I am trying to use this method inherited but does not work. I have defined the function as in OP, but it seems it doesn't count the arguments passed to `child1` or `child2`, as `len(args)` is always equal to 0. – D1X Oct 27 '16 at 18:33
  • `*args* work for functions which do not have restriction on amount of parameters passed. So you have to explicitly pass the pass the parameters. In case you do not want to do that, you have to store the list within the class as the object variable. In that case go with [*Tryph's Answer*](http://stackoverflow.com/a/40284279/2063361) – Moinuddin Quadri Oct 27 '16 at 18:43
1

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.
  • The lambda function returns False when provided with a negative number.
  • The all function returns True if all elements in the given list are True.
Tryph
  • 5,946
  • 28
  • 49