我在python中遇到了未绑定方法错误,代码如下
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
来使代码正常工作。我是蟒蛇新手。有人能解释一下为什么要定义静态方法吗?或者,为什么不是所有的方法都定义为静态方法?
发布于 2010-03-13 22:14:41
静态方法的用途有限,因为它们不能访问类实例的属性(像常规方法一样),也不能访问类本身的属性(像类方法一样)。
因此,它们对于日常方法并不有用。
但是,它们对于将一些实用函数与一个类组合在一起可能很有用-例如,从一种类型到另一种类型的简单转换-除了提供的参数之外,不需要访问任何信息(可能还有一些模块全局的属性)。
它们可以放在类之外,但将它们分组在类内可能有意义,因为它们只在类中适用。
您还可以通过实例或类引用方法,而不是模块名称,这可以帮助读者了解方法与哪个实例相关。
发布于 2010-03-13 23:45:24
这不是你实际问题的重点,但既然你说你是python新手,也许这会有帮助,而且没有其他人站出来明确地说出这一点。
我永远不会通过将方法设置为静态方法来修复上面的代码。我要么放弃这个类,只写一个函数:
def drawSample(samplesize,List):
sample=random.sample(List,samplesize)
return sample
Choices=range(100)
print drawSample(5,Choices)
如果您有许多相关的函数,您可以将它们分组到一个模块中-即,将它们全部放在同一个文件中,例如,名为sample.py
;然后
import sample
Choices=range(100)
print sample.drawSample(5,Choices)
或者我会在类中添加一个__init__
方法,并创建一个包含有用方法的实例:
class Sample(object):
'''This class defines various methods related to the sample'''
def __init__(self, thelist):
self.list = thelist
def draw_sample(self, samplesize):
sample=random.sample(self.list,samplesize)
return sample
choices=Sample(range(100))
print choices.draw_sample(5)
(我还更改了上面示例中的大小写约定,以匹配PEP 8推荐的样式。)
Python的优点之一是,它不会强迫您使用类来处理所有事情。只有当存在应该与方法关联的数据或状态时,才能使用它们,这就是类的用途。否则,您可以使用函数,这就是函数的用途。
发布于 2010-03-13 21:51:13
当你从一个对象实例中调用一个函数对象时,它就变成了一个“绑定方法”,并且实例对象本身被作为第一个参数传入。
在对象实例上调用classmethod
对象(包装函数对象)时,实例对象的类将作为第一个参数传入。
调用staticmethod
对象(包装函数对象)时,不会使用隐式的第一个参数。
class Foo(object):
def bar(*args):
print args
@classmethod
def baaz(*args):
print args
@staticmethod
def quux(*args):
print args
>>> foo = Foo()
>>> Foo.bar(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method bar() must be called with Foo instance as first argument (got int instance instead)
>>> Foo.baaz(1,2,3)
(<class 'Foo'>, 1, 2, 3)
>>> Foo.quux(1,2,3)
(1, 2, 3)
>>> foo.bar(1,2,3)
(<Foo object at 0x1004a4510>, 1, 2, 3)
>>> foo.baaz(1,2,3)
(<class 'Foo'>, 1, 2, 3)
>>> foo.quux(1,2,3)
(1, 2, 3)
https://stackoverflow.com/questions/2438473
复制相似问题