Reputation: 201
I have a two different classes (A & B for example), and I'm trying to take an instance of class A as a parameter in class B. Edit: I'm trying to create the instance within the constructor of Class B so that I can use it for subsequent methods in Class B.
Basically this:
class A(object):
def __init__(self, various arguments):
self.a_arguments = arguments
class B(object):
def __init__(self, various arguments):
self.b_arguments = arguments
self.a = A(arguments of A)
In this case, how can I list the "arguments of A" when trying to create the instance self.a? When I write the arguments as self.a_arguments, they can't be accessed because they are in Class A and not Class B. When I tried just a_arguments, I get an error that the a_arguments are not defined. Yet I don't want to have to rewrite all the self.a_arguments in the Class B constructor just so I can use them to create an instance of A.
Upvotes: 2
Views: 10443
Reputation: 448
If you want to pass some indeterminate number of arguments to something, you should use tuple unpacking. Here is some code:
class A(object):
def __init__(self, *args):
self.one, self.two, self.three_or_more = *args
class B(object):
def __init__(self, arg_for_b, arg2_for_b, *a_args):
self.ab = arg_for_b
self.ab2 = arg2_for_b
self.a = A(*a_args)
How does this work?
Class A
takes any number of arguments via the splat (*
) operator. Using tuple unpacking (*var
), the fields of the class one
, two
, and three_or_more
are assigned to the first, second, and remaining elements of the input arguments.
These could be passed as foo = A(1,2,3,4,5,6,7,8,9...inf)
, by putting *args
in the constructor, there can be any number of args and they are not forced to be in a list or tuple.
B
takes two arguments for itself, and the remaining arguments are splat'd into a set to pass to A
.
In usage:
>>> from module import A,B
foo = B(1,2,3,4,5)
A note on design -- it is probably a bad idea to initialize another class inside one class constructor. It would probably be easier to understand if the code looked like this:
class A(object):
def __init__(self, *args):
self.one, self.two, self.three = *args
class B(object):
def __init__(self, arg_for_b, arg2_for_b, A_obj):
self.ab = arg_for_b
self.ab2 = arg2_for_b,
self.a = A_obj
>>> from module import A,B
foo = B(1,2,A(3,4,5))
Upvotes: 5
Reputation: 56
I would suggest providing the constructor for B an initialised object of type A, e.g.:
class B(object):
def __init__(self, objectA):
self.b_arguments = arguments
self.a = objectA
objectB = B(A(<args>))
Upvotes: 2