Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class callback doesn't work after defining variables

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading