[英]Can I have a simple list of a dataclass field
Can I have easily a list of field from a dataclass
?我可以轻松获得
dataclass
中的字段列表吗?
@dataclass
class C:
x: int
y: int
z: int
t: int
expected result:预期结果:
[x,y,z]
you can use the asdict method of dataclass
.您可以使用
dataclass
的asdict方法。
if you want the keys:如果你想要钥匙:
obj.asdict().keys()
or if you want the value of the fields:或者如果您想要字段的值:
obj.asdict().values()
Both methods above return a View
object which you can iterate on, or you can convert it to list
using list(...)
.上述两种方法都返回一个
View
object ,您可以对其进行迭代,也可以使用list(...)
将其转换为list
。
The answer depends on whether or not you have access to an object of the class.答案取决于您是否有权访问 class 的 object。
If you only have access to the class, then you can use dataclasses.fields(C)
which returns a list of field objects (each of which has a .name
property):如果您只能访问 class,那么您可以使用 dataclasses.fields
dataclasses.fields(C)
返回字段对象列表(每个对象都有一个.name
属性):
[field.name for field in dataclasses.fields(C)]
If you have a constructed object of the class, then you have two additional options:如果您有 class 的构造 object,那么您有两个额外的选择:
dataclasses.fields
on the object:dataclasses.fields
上使用 dataclasses.fields:[field.name for field in dataclasses.fields(obj)]
dataclasses.asdict(obj)
(as pointed out by this answer ) which returns a dictionary from field name to field value.dataclasses.asdict(obj)
(正如这个答案所指出的),它返回一个从字段名到字段值的字典。 It sounds like you are only interested in the .keys()
of the dictionary:.keys()
感兴趣:dataclasses.asdict(obj).keys() # gives a dict_keys object
list(dataclasses.asdict(obj).keys()) # gives a list
list(dataclasses.asdict(obj)) # same
Here are all of the options using your example:以下是使用您的示例的所有选项:
from dataclasses import dataclass, fields, asdict
@dataclass
class C:
x: int
y: int
z: int
t: int
# from the class
print([field.name for field in fields(C)])
# using an object
obj = C(1, 2, 3, 4)
print([field.name for field in fields(obj)])
print(asdict(obj).keys())
print(list(asdict(obj).keys()))
print(list(asdict(obj)))
Output: Output:
['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
dict_keys(['x', 'y', 'z', 't'])
['x', 'y', 'z', 't']
['x', 'y', 'z', 't']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.