Class callback doesn't work after defining variables

Question:

I am trying to call back a class method within another class. It works fine if I don’t define the variable x,y,z (see commented portion) while creating objects. However, if I explicitly define the variable names, it doesn’t work. Wondering what’s making this happen?

class ClassA():
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def method_a(self):
        return f'A, method_a, {self.a}, {self.b}'

    def callback_method(self, *args):
        obj = ClassB(*args)
        return obj.method_b()


class ClassB():
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def method_b(self):
        return f'B, method_b, {self.x}, {self.y}, {self.z}'


A = ClassA(a=1, b=2)
print(A.method_a())
# A, method_a, 1, 2

B = ClassB(x=3, y=4, z=5)
print(B.method_b())
# B, method_b, 3, 4, 5

print(A.callback_method(10, 11, 12))
# B, method_b, 10, 11, 12

# print(A.callback_method(x=10, y=11, z=12)) # <------ doesn't work

Asked By: beta green

||

Answers:

You defined the callback_method to only accept positional arguments with *args but no keyword arguments.

Instead you can make it accept both & pass it on to ClassB in order to make sure you can call it with either positional or keyword arguments:

class ClassA():
    ...

    def callback_method(self, *args, **kwargs):
        obj = ClassB(*args, **kwargs)
        return obj.method_b()

Result:

print(A.callback_method(x=10, y=11, z=12))  # Output: 'B, method_b, 10, 11, 12'

Answered By: rdas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.