Python 2.7初学者错误:未绑定方法

时间:2013-03-22 04:14:07

标签: python

我刚开始学习python,最近在学习的时候遇到了一个问题 类。 请看一下代码。

class Critter(object):
    """your very own bug generator"""
    total=0
    def status(x):
        print Critter.total
        status=staticmethod(status)
    def __init__(self,name):
        print'a critter has been created'
        self.name=name
        Critter.total+=1


crit1=Critter('pooch')
crit2=Critter('Duff')
crit3=Critter('pluto')

Critter.status()
print'\nAccessing the class attributes through an object:',crit1.total

运行代码后出现此错误:

line 19, in <module>
Critter.status(Critter.total)
TypeError: unbound method status() must be called with Critter instance as first  
argument(got int instance instead)

我仍然不清楚绑定/解绑如何工作。对于初学者提出的问题,对于给予的任何帮助都不胜感激。

2 个答案:

答案 0 :(得分:1)

您的代码存在以下问题:

  • 缩进问题。您定义的任何需要绑定到类(即属于类)的变量或方法需要在类下缩进一级。
  • status=staticmethod(status)需要在类下直接定义,而不是在status()方法定义的范围内。由于status是指Critter.status()
  • 至少根据您展示的status()来电,x方法不应采用任何参数Critter.status()

您看到的上述错误表明python无法识别您的类定义中的staticmethod调用,因为它的缩进不正确。所以python刚刚将status()方法定义为纯粹的实例方法(这是默认方法)。例如,方法,python期望第一个参数是实例句柄。

这应该有效:

class Critter(object):
    """your very own bug generator"""
    total=0

    def status():
        print Critter.total
    status=staticmethod(status)

    def __init__(self,name):
        print 'a critter has been created'
        self.name=name
        Critter.total+=1

crit1=Critter('pooch')
crit2=Critter('Duff')
crit3=Critter('pluto')

Critter.status()
print'\nAccessing the class attributes through an object:',crit1.total

<强>输出:

a critter has been created
a critter has been created
a critter has been created
3

Accessing the class attributes through an object: 3

如果你正在使用python&gt; 2.4(可能是这种情况),您可以使用@staticmethod装饰器来定义静态方法,如下所示:

class Critter(object):
    """your very own bug generator"""
    total=0

    @staticmethod
    def status():
        print Critter.total

    def __init__(self,name):
        print 'a critter has been created'
        self.name=name
        Critter.total+=1

答案 1 :(得分:0)

将您的代码更改为:

class Critter(object):
    """your very own bug generator"""

    total = 0

    @staticmethod
    def status():
        print Critter.total

    def __init__(self,name):
        print 'a critter has been created'
        self.name = name
        Critter.total += 1

要查找有关绑定和未绑定方法的更多信息,请尝试阅读此Class method differences in Python: bound, unbound and static