Home > database >  Problem finding array entry based on object attribute
Problem finding array entry based on object attribute

Time:11-01

i have been having problems with a function useing an object as an input, but not knowing the position of the object, so i have made a stripped down version of the code to exemplyfi

sett = []


class Test:
    def __init__(self, name, number):
        self.name = name
        self.num = num

    @staticmethod
    def howmany(who):
        print(who.number)


sett.append(Test('dog', 2))
sett.append(Test('cat', 5))
sett.append(Test('fish', 7))
Test.howmany(sett.index(Test.name == 'dog'))

if it worked at intended this would output '2' as that is the number of the object with name 'dog'.

pleas help thanks

CodePudding user response:

Your code has a mix up between num and number. Besides that necessary fix, the index method returns ... an index, not a member of sett. Moreover, Test.name is wrong: Test is your class object, not an instance. You could use the next function to get a matching item.

As a side note: you can just create the list of three items in one go. There is no reason to call append repeatedly:

class Test:
    def __init__(self, name, number):
        self.name = name
        self.number = number  # fix

    @staticmethod
    def howmany(who):
        print(who.number)

sett = [Test('dog', 2), Test('cat', 5), Test('fish', 7)]
Test.howmany(next(test for test in sett if test.name == 'dog'))

Another note: it is not clear to me why you want to define howmany as a static method and not as an instance method, unless you would foresee that who could be None, but that logic is currently missing.

  • Related