【问题标题】:How to change method implementation without changing it to be not static如何更改方法实现而不将其更改为非静态
【发布时间】:2017-06-25 13:38:04
【问题描述】:

例如:

class a:
    @staticmethod
    def aaa():
        print 'a'

a.aaa()
a.aaa = lambda: raise ValueError('a')
a.aaa()

python 第二次引发我没有将类 a 的实例传递给方法的错误。 如何在不删除静态属性的情况下更改实现?

【问题讨论】:

    标签: python python-2.7 lambda static-methods


    【解决方案1】:

    直接调用staticmethod装饰器就可以了

    class a:
        @staticmethod
        def aaa():
            print 'a'
    
    a.aaa()
    # decorate the lambda expression with staticmethod
    a.aaa = staticmethod(lambda: 'a')
    a.aaa()

    这基本上就是你在使用装饰器时所做的。

    请注意,您不能直接raise 出错,因为raise语句,而不是表达式。不过你可以use some tricks to raise an exception in a lambda expression

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      相关资源
      最近更新 更多