Python 如何有效地格式化类内部方法的输出?
我想写一个里面有很多东西的类。现在,我想为输出提供一些选项,以便以指定格式显示数据。在我的示例中,类中的函数应该将输出(以前的字典)格式化为列表。但我真的不知道怎么做 以下是我的尝试:Python 如何有效地格式化类内部方法的输出?,python,Python,我想写一个里面有很多东西的类。现在,我想为输出提供一些选项,以便以指定格式显示数据。在我的示例中,类中的函数应该将输出(以前的字典)格式化为列表。但我真的不知道怎么做 以下是我的尝试: class TestClass(object): def __init__(self): pass def return_values_as_list(self,otherfunction): data_as_list=[ i for i in otherfunc
class TestClass(object):
def __init__(self):
pass
def return_values_as_list(self,otherfunction):
data_as_list=[ i for i in otherfunction.values()]
return data_as_list
def get_data1_from_db(self):
self.data= {'1_testkey':'1_testvalue',"1_testkey2":"1_testvalue2"}
def get_data2_from_db(self):
self.data= {'2_testkey':'2_testvalue',"2_testkey2":"2_testvalue2"}
return self.data
最后我想要的是
['1_testvalue','1_testvalue2']
当实例化如下所示时:
testcase = TestClass()
testcase.get_data1_from_db.return_values_as_list()
有什么帮助吗?我也想到了钩子…但我真的不知道怎么做
def return_values_as_list(self,otherfunction):
data_as_list= otherfunction().values()
return data_as_list
您就快到了-您只需要调用函数(添加括号)
实例化为:
testcase.return_values_as_list(testcase.get_data1_from_db)
我认为类
get…
方法应该是属性
class TestClass(object):
def __init__(self):
pass
@property
def get_data1_from_db(self):
data= {'1_testkey':'1_testvalue',"1_testkey2":"1_testvalue2"}
return data.values()
@property
def get_data2_from_db(self):
data= {'2_testkey':'2_testvalue',"2_testkey2":"2_testvalue2"}
return data.values()
testcase = TestClass()
print testcase.get_data1_from_db # ['1_testvalue', '1_testvalue2']
print testcase.get_data2_from_db # ['2_testvalue', '2_testvalue2']
看到这个问题:谢谢你的链接…这个例子看起来怎么样?…对于我和完整性-菲斯蒂夫!谢谢你的回答!但是,是否有可能以某种方式使用点语法…我不需要再次调用段落中的对象?…只是一个简单的。返回\u值\u作为\u列表()左右。。。?塔克斯!