__getattr__等效于CLASS方法

时间:2014-09-15 10:29:17

标签: python

当找不到属性/方法(instance.something)时,我们可以通过实现__getattr__方法来解决它。 我的问题是,如果找不到类方法,我们如何解决。

class foo(object):
    @classmethod
    def bar(cls,a):
        print a

foo.bar("123")

# How to make below line work without throwing =  AttributeError: type object 'foo' has no attribute 'bar1'
foo.bar1("234")

实时例子:
@goncalopp:基本上我们有一个主库(比如foo),它导入了各种其他类/ lib而不是,在一个非常具体的“怪异”的情况下,我不应该导入那个主库,所以我需要实现一个很少的方法用最少的代码破解并使下线工作。例如,self.foo.bar.Comment(“打印此评论”)和self.foo.bar.Log(“打印此日志”),就像我们有INFO,DEBUG,ERROR ...... 我的看法是:

foo = None
class Dummyfoo(object):
    class foo(object):  
        class bar(object):

            @classmethod
            def Comment(cls,a):
                print a

if foo == None:
    self = Dummyfoo()
    self.foo.bar.Comment("print this comment")  

所以实现这一目标的一种方法是实现INFO,DEBUG ...或一个停止类方法,它们将打印它所提供的任何内容。

希望现在问题及其目的更有意义。

感谢。

0 个答案:

没有答案
相关问题