英文:
How do I Iteratively set the @property decorator for every value in a list?
问题
以下是翻译好的部分:
我有一个主要用于存储对类的其他属性进行的计算的类。但是,我希望进行多个计算,其中n不同,并将每个计算都设置为类的新属性。
下面的代码示例显示了为单个值设置属性的示例。
@dataclass
class A:
@property
def set_property_5(self):
return self.method(5)
def method(self, n):
return n * 2
我想要做的是以下内容(这不起作用,但我认为这很好地说明了我的目的):
@dataclass
class A:
for n in [5, 10, 15]:
@property
def set_property_n(self):
return self.method(n)
def method(self, n):
return n * 2
我应该如何解决这个问题?以及在下面的示例中设置每个n值的属性的最佳实践是什么?
英文:
I have a class that is mainly used to store calculation made on other attributes of the class. However, I want to do multiple calculations where n differs and set every calculation as a new attribute of the class.
The code below shows an example of setting the attribute for a single value.
@dataclass
class A:
@property
def set_property_5(self):
return self.method(5)
def method(self, n):
return n * 2
What I want to do is the following (This doesn't work, but I think this illustrates my purpose well):
@dataclass
class A:
for n in [5, 10, 15]:
@property
def set_property_n(self):
return self.method(n)
def method(self, n):
return n * 2
How should I tackle this problem? and what is the best practice in setting the attributes for every value of n in the example below?
答案1
得分: 1
Sure, here's the translated code:
我认为这样做是否值得有疑问,但你可以:
```python
from dataclasses import dataclass
@dataclass
class A:
def method(self, n):
return n * 2
for n in [5, 10, 15]:
setattr(A, f"set_property_{n}", property(lambda self, _n=n: self.method(_n)))
#测试:
print(A().set_property_10)
另一种方法可能是在这里使用 namedtuple
。为此,创建名称、函数和它们的参数的列表,然后应用函数并将结果与属性名称连接:
from collections import namedtuple
def calc(n):
return n * 2
n_list = [5, 10, 15]
names = [f"set_property_{n}" for n in n_list]
funcs = [calc] * 3
args = [(n,) for n in n_list]
result = [f(*a) for f, a in zip(funcs, args)]
A = namedtuple("A", names)
a = A._make(result)
print(a)
输出:
A(set_property_5=10, set_property_10=20, set_property_15=30)
这是您要的代码的翻译部分。
<details>
<summary>英文:</summary>
I think it's questionable if you should do this but you can:
from dataclasses import dataclass
@dataclass
class A:
def method(self, n):
return n * 2
for n in [5, 10, 15]:
setattr(A, f"set_property_{n}", property(lambda self, _n=n: self.method(_n)))
#Test:
print(A().set_property_10)
An alternative may be to use `namedtuple` here. For this, lists of names, functions and their arguments are created, then functions applied and results joined with the attribute names:
from collections import namedtuple
def calc(n):
return n * 2
n_list = [5, 10, 15]
names = [f"set_property_{n}" for n in n_list]
funcs = [calc] * 3
args = [(n,) for n in n_list]
result = [f(*a) for f, a in zip(funcs, args)]
A = namedtuple("A", names)
a = A._make(result)
print(a)
Output:
A(set_property_5=10, set_property_10=20, set_property_15=30)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论