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?