相关疑难解决方法(0)

3360
推荐指数
24
解决办法
73万
查看次数

Python中的类方法差异:绑定,未绑定和静态

以下类方法有什么区别?

是一个是静态而另一个不是?

class Test(object):
  def method_one(self):
    print "Called method_one"

  def method_two():
    print "Called method_two"

a_test = Test()
a_test.method_one()
a_test.method_two()
Run Code Online (Sandbox Code Playgroud)

python

233
推荐指数
4
解决办法
15万
查看次数

为什么我们使用@staticmethod?

我只是不明白为什么我们需要使用@staticmethod.让我们从一个例子开始吧.

class test1:
    def __init__(self,value):
        self.value=value

    @staticmethod
    def static_add_one(value):
        return value+1

    @property
    def new_val(self):
        self.value=self.static_add_one(self.value)
        return self.value


a=test1(3)
print(a.new_val) ## >>> 4



class test2:
    def __init__(self,value):
        self.value=value

    def static_add_one(self,value):
        return value+1

    @property
    def new_val(self):
        self.value=self.static_add_one(self.value)
        return self.value


b=test2(3)
print(b.new_val) ## >>> 4
Run Code Online (Sandbox Code Playgroud)

在上面的示例static_add_one中,两个类中的方法在计算中不需要类(self)的实例.

该方法static_add_one在类test1是由装饰@staticmethod和正常工作.

但与此同时,static_add_onetest2中没有@staticmethod装饰的方法也可以通过使用self在参数中提供但完全不使用它的技巧来正常工作.

那么使用的好处是@staticmethod什么?它会改善性能吗?或者仅仅是因为python的禅宗指出" 明确比隐含更好 "?

python

5
推荐指数
2
解决办法
2487
查看次数

什么是python中的“静态方法”

我对python很陌生,无法理解python中的静态方法是什么(例如__new__())以及它有什么作用。谁能解释一下?太感谢了

python static-methods

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

标签 统计

python ×4

methods ×1

oop ×1

python-decorators ×1

static-methods ×1