2

I want to write a class with much stuff inside. Right now I want to have certain options for the output to show data in a disired format. Im my example a function inside a class should format the output (a former dictionary) as a list. But i really can't figure out how to do it...

here my try:

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 

What i want to have at the end is something like

['1_testvalue','1_testvalue2']

when instantiation looks like the following:

testcase = TestClass()
testcase.get_data1_from_db.return_values_as_list()

Any help with that? I thought also of hooks...but i dont really know how to do that...

Jurudocs
  • 8,595
  • 19
  • 64
  • 88

2 Answers2

1
def return_values_as_list(self,otherfunction):
    data_as_list= otherfunction().values()
    return data_as_list

You were almost there - you just needed to call the function (add parentheses)

Instantiate with:

testcase.return_values_as_list(testcase.get_data1_from_db)
Steve Mayne
  • 22,285
  • 4
  • 49
  • 49
  • hi Steve! Thanks for your answer! But is it possible to have the Dot syntax somehow...that i dont need to call the object inside of the para again?...just a simple .return_values_as_list() or so...? Thanx! – Jurudocs Nov 04 '12 at 13:41
1

I think your class get... methods should be property attributes.

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']
martineau
  • 119,623
  • 25
  • 170
  • 301