为类属性指定一个短名称

2024-09-29 01:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个Python包来读取某些类型的数据。它从数据中创建属性,以便轻松访问与数据相关的元信息

如何为属性创建短名称

基本上,我们假设包名是read_data,它有一个名为data_header_infomation_x_location的属性

import read_data
my_data = read_data(file_path)

如何为该属性创建一个短名称

x = "data_header_infomation_x_location"

my_data[1].x给出错误无属性

以下是我的案例的完整示例

from obspy.io.segy.core import _read_segy

file_path = "some_file_in_my_pc)
sgy = _read_segy(file_path, unpack_trace_headers=True)

sgy[1].stats.segy.trace_header.x_coordinate_of_ensemble_position_of_this_trace

最后一行给出了一个数字。e、 g.,x位置

我想要的是用一个短名称重命名所有这些长嵌套属性stats.segy.trace_header.x_coordinate_of_ensemble_position_of_this_trace

举个例子

attribute = "stats.segy.trace_header.x_coordinate_of_ensemble_position_of_this_trace"

getattr(sgy[1], attribute )

不起作用


Tags: of数据path名称coordinatereaddata属性
1条回答
网友
1楼 · 发布于 2024-09-29 01:32:44

怎么样:

from obspy.io.segy.core import _read_segy

attribute_tree_x = ['stats', 'segy', 'trace_header', 'x_coordinate_of_ensemble_position_of_this_trace']

def get_nested_attribute(obj, attribute_tree):
    for attr in attribute_tree:
        obj = getattr(obj, attr)
    return obj

file_path = "some_file_in_my_pc"
sgy = _read_segy(file_path, unpack_trace_headers=True)

sgy[1].stats.segy.trace_header.x_coordinate_of_ensemble_position_of_this_trace
x = get_nested_attribute(sgy[1], attribute_tree_x) # should be the same as the line above

您不能一次性请求属性的属性,但这会在层之间循环以获得您要查找的最终值

相关问题 更多 >