我想获取在运行时传递给 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
预期输出:
{
"name": "str",
"add": "str"
}
如果要返回类中任意名称的变量,可以使用
getattr()
返回变量,或者返回 None
。
文档:
getattr(对象,名称,默认)
返回指定属性的值 的对象。名称必须是字符串。如果字符串是其中之一的名称 对象的属性,结果是该属性的值。 例如, getattr(x, 'foobar') 相当于 x.foobar
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()
这将安全地获取变量(如果存在),否则不会返回任何内容。