-3

example code of the problem: example code of the problem \ error: the error

I try to do this to reduce repetition of my code but it doesn't work. I want to use take variable to represent either pop or serve. Is there a way to make this work? This might looks unnecessary but the real code I am having problem is quite long and it looks very repetitive if I put them in if else block. Instead of putting the return statement into if else block, I want to set a variable of the method instead.

  • Answer: yes, there is a way. Maybe you also want to ask a better question after you included your code as code. Also: beware of the [mutable default argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) – Thomas Weller Sep 17 '21 at 04:46
  • 1
    Why don't you simply `return` inside the `if`? – Selcuk Sep 17 '21 at 04:51
  • Wow, you posted another image of text after you were told not to do that... – Thomas Weller Sep 17 '21 at 05:03
  • Do not post images. We cannot copy them or run them. A high quality question makes it easy for us to test and post high quality answers. – tdelaney Sep 17 '21 at 05:12

2 Answers2

1

For other questions always provide code in text rather than a bitmap, so it can be copied and pasted.

All you need is obj.func as the variable.

class A:
    def func_1(self):
        print('hi')

class B:
    def func_2(self):
        print('hello there')

def test(one_or_zero):
    if one_or_zero:
        obj = A()
        func = obj.func_1
    else:
        obj = B()
        func = obj.func_2
    func()
    return

test(0)
adam
  • 51
  • 1
  • 6
1

you need to give the function linked to the object.

if one_or_zero == 1:
    obj = Stack()
    take = obj.pop
elif one_or_zero == 0:
    obj = Queue()
    take = obj.serve
else:
    ...
return take()
P.Henry
  • 11
  • 2