Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为类属性指定一个短名称_Python - Fatal编程技术网

Python 为类属性指定一个短名称

Python 为类属性指定一个短名称,python,Python,我正在使用一个Python包来读取某种类型的数据。它从数据中创建属性,以便轻松访问与数据相关的元信息 如何为属性创建短名称 基本上,让我们假设包名为read\u data,它有一个名为data\u header\u information\u x\u location的属性 import read_data my_data = read_data(file_path) 如何为该属性创建一个短名称 x = "data_header_infomation_x_location" my_data[

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

如何为属性创建短名称

基本上,让我们假设包名为
read\u data
,它有一个名为
data\u header\u information\u x\u 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
以下是我案例的完整示例

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\u header.x\u coordinate\u of theu employee\u position\u of theu this\u trace

举个例子

attribute = "stats.segy.trace_header.x_coordinate_of_ensemble_position_of_this_trace"

getattr(sgy[1], attribute )
不起作用

那么:

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

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

我认为你在问题中使用的很多词汇与你真正的意思不符。请澄清一下。