如何在 Python 中使用相同参数在 X 的子方法中实例化一个 class X?
How to instantiate a class X in a sub-method of X with the same parameters in Python?
我有以下示例代码:
class X:
def __init__(self, value):
self.value = value
def method_a(self):
...
我现在想在method_a[=32=中实例化一个X的新对象],重复使用value
,即
def method_a(self):
x = X(value = self.value)
现在,假设我要在 X
的构造函数中设置 几个 参数 。有没有一种 "pythonic" 方法可以一次性 re-set/copy 所有参数?类似于:
def method_a(self):
x = X(self)
后者不起作用(“_init__() 缺少 1 个必需的位置参数”)。我在文档中也找不到解决此问题的方法。
copy
模块可能是您所需要的:
代码
def method_a(self):
return copy.copy(self)
更好的控制:
在各种情况下,您可能只需要复制一些参数,可以使用 unpacking of argument lists combined with 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
我有以下示例代码:
class X:
def __init__(self, value):
self.value = value
def method_a(self):
...
我现在想在method_a[=32=中实例化一个X的新对象],重复使用value
,即
def method_a(self):
x = X(value = self.value)
现在,假设我要在 X
的构造函数中设置 几个 参数 。有没有一种 "pythonic" 方法可以一次性 re-set/copy 所有参数?类似于:
def method_a(self):
x = X(self)
后者不起作用(“_init__() 缺少 1 个必需的位置参数”)。我在文档中也找不到解决此问题的方法。
copy
模块可能是您所需要的:
代码
def method_a(self):
return copy.copy(self)
更好的控制:
在各种情况下,您可能只需要复制一些参数,可以使用 unpacking of argument lists combined with 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