Reputation: 2257
Please forgive the bad title - I had a hard time trying to think of a concise way to explain this.
I have a Python class that will have some underlying objects of other classes. I want to be able to create these underlying objects via a method of the original object. Let me try to explain better with an example:
class Foo:
def __init__(self):
self.bars = []
def Bar(self, a, b, c):
self.bars.append(Bar(a, b, c))
class Bar:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
I would use the above as such:
f = Foo()
f.Bar(1, 2, 3)
So this works how I want but is kind of crappy with respect to maintenance. Is there a nice "Pythonic" way to do this that would make maintaining this easy? For instance, let's say I changed the constructor of Bar
to:
__init__(self, a, b, c, d):
would there be a way to define all of this so I don't have to update the argument list in 3 places?
Upvotes: 0
Views: 141
Reputation: 879571
Sure, no problem: Just pass *args and **kwargs on to Bar
:
class Foo:
def __init__(self):
self.bars = []
def append_bar(self, *args, **kwargs):
self.bars.append(Bar(*args, **kwargs))
class Bar:
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d
f=Foo()
f.append_bar(1,2,3,4)
PS. I changed the name of the method to append_bar
because the usual convention in Python is to use lowercase names for methods, and I think methods whose names are verbs help describe what the method does.
Upvotes: 3