我有一个类Foo
其中包含Bar
类型的数据项。我无法制作一个广义的“默认”Bar.__init__()
- 将Bar
对象传递给Foo.__init__()
方法。声明类对象数据类型
如何告诉Python我想要这种类型的数据仓库?
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
这个工作,当我传入“默认”的值如图所示。但是,当我打电话getBar
,我做而不是找回我在Foo.__init__()
函数中通过的一个 - 我得到“默认”值。
b = Bar(1,2,3)
f = Foo(b)
print f.getBar().a, f.getBar().b, f.getBar().c
该吐出0 0 0
,不1 2 3
,就像我期待的。
如果我不打扰声明myBar
变量,我在getBar(self):
方法(Foo instance has no attribute 'myBar'
)中出现错误。
什么是在我的对象中使用自定义数据存储的正确方法?
听起来像这个问题是你的Bar类而不是Foo。那是什么课程? – 2012-08-10 14:41:17