我有一个 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 实例没有属性 'myBar '
).
在我的对象中使用自定义数据成员的正确方法是什么?
最佳答案
您不需要告诉 Python 您将要添加某个数据成员——只需添加它即可。 Python比例如更动态Java 在这方面。
如果 bar
实例本质上是不可变的(意味着它们在实践中没有改变),您可以将默认实例作为 __init__()
参数的默认值:
class Foo:
def __init__(self, the_bar=Bar(0,0,0)):
self.my_bar = the_bar
所有使用默认值的 Foo
实例将共享一个 Bar
实例。如果 Bar
实例可能会被改变,这可能不是你想要的,在这种情况下你应该使用这个习惯用法:
class Foo:
def __init__(self, the_bar=None):
if the_bar is None:
the_bar = Bar(0,0,0)
self.my_bar = the_bar
请注意,您通常不应在 Python 中编写 getter 和 setter。它们只是不必要的样板代码,会减慢您的应用程序。由于 Python 支持属性,因此您也不需要它们面向 future 。
关于python - 声明类对象数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11903890/