需要在运行时获取模式定义

问题描述 投票:0回答:1

我想在运行时获取传递给 get_schema 方法的表的 python 模式定义。

` 课堂测试:

def __init__(self):
    self.schema_table1 = {
        "name": "str",
        "add": "str"
    }
    self.schema_table2 = {
        "n1": "str",
        "n2": "str"
    }

def get_schema(self, table_name):
    schema = table_name
    return schema

测试2类:

def __init__(self):
    self.test_obj = Test()

def process(self):
    table_name = "schema_"+'table1'
    print(self.test_obj.get_schema(table_name))

test2_obj = Test2() test2_obj.process()

实际产量

schema_table1

**预期输出**

{ “名称”:“str”, “添加”:“str” }

python python-3.x python-2.7
1个回答
0
投票

如果要返回类中任意名称的变量,可以使用

getattr()
返回变量,或者返回
None

class Test:
    def __init__(self):
        self.schema_table1 = {
            "name": "str",
            "add": "str"
        }
        self.schema_table2 = {
            "n1": "str",
            "n2": "str"
        }

    def get_schema(self, table_name):
        schema = getattr(self, table_name, None)
        return schema

class Test2:
    def __init__(self):
        self.test_obj = Test()

    def process(self):
        table_name = "schema_" + 'table1'
        print(self.test_obj.get_schema(table_name))

test2_obj = Test2()
test2_obj.process()

这将安全地获取变量(如果存在),否则不会返回任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.