2016-11-24 95 views
0

请原谅我的noob地位,但我遇到了一个我不太了解的构造,希望有人能为我解释。嘲讽继承方法

class Base(object): 
    def mogrify(self, column): 
     return self.mogrifiers.get(column.lower().strip()) or (lambda x: x) 

...

class MyClass(some.package.Base): 
    def mogrifiers(self): 
     return { 
      'column1': (lambda x: datetime.datetime.fromtimestamp(int(x))) 
     } 

...

class MyOtherClass(object): 
    def convert_columns: 
     ... 
     new_row[colkey] = self.myclass.mogrify(colkey)(value) 

这一切工作,但我试图写一个单元测试,并模拟出MyClass

据我所知,mogrifiers返回所有列和任何所需的转换字典。

我正在测试的代码调用mogrify(从Base类继承)与字符串中的特定列名称。

这试图从字典中提取列并返回lambda函数?或者如果它不存在于字典中,它会返回一个只给出字符串的lambda表达式?

所以,我只是在我试图测试的代码中留下了(值)位。目前尚不清楚它的功能。

如果我不想测试底层的转换/转换,我的模拟可能会返回简单的lambda。

所以我这样做,但将在电话会议上的例外mogrify说:

E TypeError: 'str' object is not callable

任何人都可以提供一些线索什么,我在这里失踪?

回答

0

As far as I can tell, mogrifiers returns a dictionary of all the columns and any transformations that are required.

这是正确的,但正如你已经表明它会创建一个新的字典,每次看起来没有必要。

The code I am testing calls mogrify (inherited from the Base class) with a specific column name in a string.

This tries to extract the column from the dictionary and returns the lambda function ? or if it doesn't exist in the dictionary, it returns a lambada that just gives the string back ?

是的,这也是正确的(除了拉姆达达是一个舞蹈,但我认为你的意思是再次拉姆达)。

So that just leaves me with the (value) bit in the code I'm trying to test. It's no clear what it does.

呼叫self.myclass.mogrify(colkey)返回Callable的(value)简单地调用它。

fn = self.myclass.mogrify(colkey) 
new_row[colkey] = fn(value) 

拆分成两行也将使其更清晰的问题是否与呼叫self.myclass.mogrify(colkey)fn(value):如果我重写这样可能更清晰。如果看起来很可能是fn(value)这意味着你的模拟mogrify返回str而不是返回一个可调用的;但它可能是,你得到了模拟错误和嘲笑mogrify方法实际上是一个字符串。

我建议你重写如图所示,并在两行之间插入一个print,看看实际返回的是什么。