I have a class Foo which contains a datamember of type Bar. I can’t make a generalized, “default” Bar.__init__() – the Bar object is passed into the Foo.__init__() method.
How do I tell Python that I want a datamember of this type?
class Foo:
# These are the other things I've tried, with their errors
myBar # NameError: name 'myBar' is not defined
Bar myBar # Java style: this is invalid Python syntax.
myBar = None #Assign "None", assign the real value in __init__. Doesn't work
#####
myBar = Bar(0,0,0) # Pass in "default" values.
def __init__(self, theBar):
self.myBar = theBar
def getBar(self):
return self.myBar
This works, when I pass in the “default” values as shown. However, when I call getBar, I do not get back the one I passed in in the Foo.__init__() function – I get the “default” values.
b = Bar(1,2,3)
f = Foo(b)
print f.getBar().a, f.getBar().b, f.getBar().c
This spits out 0 0 0, not 1 2 3, like I’m expecting.
If I don’t bother declaring the myBar variable, I get errors in the getBar(self): method (Foo instance has no attribute 'myBar').
What’s the correct way to use a custom datamember in my object?
You don’t need to tell Python you are going to add a certain data member – just add it. Python is more dynamic than e.g. Java in this regard.
If
barinstances are essentially immutable (meaning they are not changed in practice), you can give the default instance as default value of the__init__()parameter:All
Fooinstances uisng the default value will share a singleBarinstance. If theBarinstance might be changed, this is probably not what you want, and you should use this idiom in this case:Note that you shouldn’t usually write getters and setters in Python. They are just unnecessary boilerplate code slowing down your application. Since Python supports properties, you also don’t need them to be future-proof.