python - 声明类对象数据类型

标签 python

我有一个 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/

相关文章:

python - 使用 Python Paramiko exec_command 执行命令时未完成

python - django-guardian和django-rules可以一起使用吗?

python - 循环中的 Selenium-chrome driver.get() 重复几次后会中断

python - Google Pub/Sub 将订阅推送到受 IAP 保护的 App Engine

python - 索引两次后如何更新 Pytorch 中的张量?

Python - 使用变量作为字符串格式化的一部分

Python - 对导入文件的更改不生效

python - 抽象模型类和多个驱动类中的 Django ForeignKey 导致名称冲突

python - 如何在 python 中使用图例和 AUC 分数在一个图中绘制多条 ROC 曲线?

python - pandas - 将数组扩展到列