gpt4 book ai didi

python - 使用静态方法有什么好处?

转载 作者:IT老高 更新时间:2023-10-28 21:34:51 30 4
gpt4 key购买 nike

我用代码在python中遇到了未绑定(bind)方法错误

import random

class Sample(object):
'''This class defines various methods related to the sample'''

def drawSample(samplesize,List):
sample=random.sample(List,samplesize)
return sample

Choices=range(100)
print Sample.drawSample(5,Choices)

在这里阅读了许多有用的帖子后,我想出了如何在上面添加 @staticmethod 以使代码正常工作。我是 python 新手。有人可以解释一下为什么要定义静态方法吗?或者,为什么不是所有的方法都定义为静态方法?

最佳答案

this article详细解释。

TL;DR

1.它消除了 self 参数的使用。

2.它减少了内存使用,因为 Python 不必实例化 bound-method对于每个实例化的对象:

>>>RandomClass().regular_method is RandomClass().regular_method
False
>>>RandomClass().static_method is RandomClass().static_method
True
>>>RandomClass.static_method is RandomClass().static_method
True

3.它提高了代码的可读性,表明该方法不依赖于对象本身的状态。

4.它允许方法覆盖,因为如果方法是在模块级别(即在类之外)定义的,则子类将无法覆盖该方法。

关于python - 使用静态方法有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2438473/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com