【问题标题】:How to instantiate a class X in a sub-method of X with the same parameters in Python?如何在Python中使用相同参数在X的子方法中实例化类X?
【发布时间】:2018-06-24 06:17:44
【问题描述】:

我有以下示例代码:

class X:
 def __init__(self, value):
  self.value = value

 def method_a(self):
  ...

我现在想在 method_a实例化一个新的 X 对象,重复使用 value,即

def method_a(self):
 x = X(value = self.value)

现在,假设我在X 的构造函数中设置了几个 参数。是否有一种“pythonic”方式来一次重新设置/复制所有参数?比如:

def method_a(self):
 x = X(self)

后者不起作用(“_init__() 缺少 1 个必需的位置参数”)。我在文档中也找不到任何解决此问题案例的方法。

【问题讨论】:

    标签: python python-3.x constructor initialization instance-variables


    【解决方案1】:

    copy 模块可能是您需要的:

    代码

    def method_a(self):
        return copy.copy(self)
    

    更精细的控制:

    在各种情况下,您可能只需要复制一些参数,可以使用unpacking of argument lists 结合getattr 来管理要复制的更长列表:

    def method_a(self):
        attributes_to_copy = ('value1', 'value2')
        kwargs = {k: getattr(self, k) for k in attributes_to_copy}
        return type(self)(**kwargs)
    

    测试代码:

    import copy
    
    class X(object):
        def __init__(self, value1, value2):
            self.value1 = value1
            self.value2 = value2
    
        def method_a(self):
            return copy.copy(self)
    
        def method_b(self):
            attributes_to_copy = ('value1', 'value2')
            kwargs = {k: getattr(self, k) for k in attributes_to_copy}
            return type(self)(**kwargs)
    
    x1 = X(1, 2)
    x2 = x1.method_a()
    x3 = x1.method_b()
    assert x1.value1 == x2.value1
    assert x1.value1 == x3.value1
    

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多