我使用以下代码在 python 中遇到了未绑定方法错误:
import random
class Sample(object):
def drawSample(samplesize, List):
sample = random.sample(List, samplesize)
return sample
Choices=range(100)
print(Sample.drawSample(5, Choices))
我能够通过添加来解决问题@staticmethod
到方法。不过,我实在不太了解情况。
使用“静态”方法有什么意义?为什么它可以解决这段代码中的问题,为什么它们是必要的?相反,我为什么要not想要这样做(即为什么需要额外的代码来使方法静态)?
See 本文详细解释。
TL;DR
1.它消除了使用self
争论。
2.它减少了内存使用,因为Python不必实例化绑定方法对于每个实例化的对象:
>>>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.它允许方法重写,因为如果该方法是在模块级别(即类外部)定义的,则子类将无法重写该方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)