我想在运行时获取传递给 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” }
如果要返回类中任意名称的变量,可以使用
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()
这将安全地获取变量(如果存在),否则不会返回任何内容。