-1

Let's say we have:

class A:
   def __init__(self):
     self.Ap1 = 'Ap1val'
     self.Ap2 = 'Ap2val'
     self.Ap3 = 'Ap3val'

class B:
   def __init__(self):
     self.Bp1 = 'Bp1val'
     self.Bp2 = 'Bp2val'
     self.Bp3 = A()

class C:
   def __init__(self):
     self.Cp1 = 'Cp1val'
     self.Cp2 = 'Cp2val'
     self.Cp3 = B()

I want to get value of given object field name with the following code:

def gp(class_inst, key):
    properties = [prop for prop in dir(class_inst) if not prop.startswith('__')]

    for prop in properties:
        value = class_inst.__getattribute__(prop)
        if isinstance(value, str):
            print('{}:{} {} {}'.format(prop, value, prop == key, key))
            if prop == key:
                print(value)
                return value
        else:
            gp(value, key)

    return None


print(gp(C(), 'Bp2'))

but in return I keep getting None even though the if returns true and it enters the right return statement.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
mCs
  • 2,591
  • 6
  • 39
  • 66

1 Answers1

0

The issue is the recursion on this line:

else:
    gp(value, key)

The prop == key test is returning a value from a recursive function that does not handle the returned value. To handle the value, you need to set your else statement to return the results of the recursion.

else:
    return gp(value, key)

This solution worked in my test.

David Scott
  • 796
  • 2
  • 5
  • 22