python - 如何让 __init__ 获取新值或现有实例?

标签 python

我有一个类似于以下的模式:

class Foobar(object):  # instances of this class will be referenced by others
    def __init__(self, value):
        self.value = value

class Foo(object):
    def __init__(self, value, foobar)
        self.value = value
        if isinstance(foobar, Foobar):
            self.foobar = foobar
        else:
            self.foobar = Foobar(foobar)

class Bar(object):
    def __init__(self, value, foobar)
        self.value = value
        if isinstance(foobar, Foobar):
            self.foobar = foobar
        else:
            self.foobar = Foobar(foobar)

这允许 FooBar 获取新值(创建 Foobar)或 Foobar 的现有实例 作为他们的 foobar 参数。


我想去掉这些冗余代码:

# ...
        if isinstance(foobar, Foobar):
            self.foobar = foobar
        else:
            self.foobar = Foobar(foobar)

我考虑了以下内容,但由于 Foobar.__new__() 中的无限递归,它不起作用:

class Foobar(object):
    def __new__(cls, value):
        if isinstance(value, cls):
           return value
        else:
           return Foobar(value)
    def __init__(self, value):
        self.value = value

class Foo(object):
    def __init__(self, value, foobar)
        self.value = value
        self.foobar = Foobar(foobar)

class Bar(object):
    def __init__(self, value, foobar)
        self.value = value
        self.foobar = Foobar(foobar)

允许类根据传递给 __init__ 的值创建新实例使用现有实例的最佳方法是什么?

最佳答案

您可以通过调用基类 __new__() 来摆脱递归:

class Foobar(object):
    def __new__(cls, value):
        if isinstance(value, cls):
           return value
        else:
           return object.__new__(cls, value)
    def __init__(self, value):
        self.value = value

请注意,__new__() 的第一个参数是一个类,而不是self

也就是说,我不认为这是一个有用的模式。通常,我建议在构造函数中接受实例并将对象构造留给调用代码。虽然做正确事情的魔法通常看起来很方便,但它通常会导致比其值(value)更多的问题。

关于python - 如何让 __init__ 获取新值或现有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348649/

相关文章:

Python Windows 无法统计包含无效字符的文件

python - Erlang 512 哈希与 python 512 哈希不匹配

Python:这会给我留下一个干净的环境吗?

python - 如何从框架中清除 Django 登录消息

python - 使用正则表达式或 lxml 在 Python 中提取 HTML 注释?

Python 尝试...除了命令行

python - 如何设置 QTableView CSS 样式

python - STDOUT 中的子进程或 commands.getstatusoutput 并存储在变量中

python - 如何按日期 (mm/dd/yyyy) 对巨大的 csv 文件中的记录进行排序?

python - 将 Pandas 与 IN 语句的元组一起使用时转义单引号