相关疑难解决方法(0)

python类设计(staticmethod vs方法)

对于不需要任何传递信息(对象实例或类)的方法,更好的方法是什么,因为例如它们只是进行简单的转换.@staticmethod还是方法

class Foo(object):
    def __init__(self, trees):
        self.money = Foo.trees2money(trees)

    @staticmethod
    def trees2money(trees):
        return trees * 1.337

class Quu(object):
    def __init__(self, trees):
        self.money = self.trees2money(trees)

    def trees2money(self, trees):
        return trees * 1.337
Run Code Online (Sandbox Code Playgroud)

python oop static-methods

7
推荐指数
1
解决办法
2787
查看次数

Lambda函数可以是类属性吗?

我想为一类的所有实例提供一些lambda函数。因此,我的想法是将lambda函数声明为类属性。在下面的简单代码中,为什么不能评估f定义为class属性的以下lambda函数?

In [1]: class MyClass():
   ...:     f = lambda x : 2 * x + 1
   ...:     def __init__(self):
   ...:         pass

In [2]: Inst = MyClass()

In [3]: MyClass.f
Out[3]: <unbound method MyClass.<lambda>>

In [4]: MyClass.f(2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-5fc154bfb75c> in <module>()
----> 1 MyClass.f(2)

TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got int instance instead)

In [5]: Inst.f(3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-90cde1a87da4> in …
Run Code Online (Sandbox Code Playgroud)

python lambda

4
推荐指数
1
解决办法
2548
查看次数

标签 统计

python ×2

lambda ×1

oop ×1

static-methods ×1