2009-10-14 50 views
0

如果你把下面的简单类:Python的新手 - 理解类函数

class AltString: 

    def __init__(self, str = "", size = 0): 
     self._contents = str 
     self._size = size 
     self._list = [str] 

    def append(self, str): 
     self._list.append(str) 

    def output(self): 
     return "".join(self._list) 

我用成功调用类的实例:

as = AltString("String1") 

as.append("String2") 

as.append("String3") 

当我然后调用使用as.output代替output功能的字符串返回,我得到以下代替:

unbound method AltString.output 

,如果我把它用as.output()我得到以下错误:

TypeError: unbound method output() must be called with 
    AltString instance as first argument (got nothing instead) 

什么我没有做对吗?

+1

您正在编写'StringIO.StringIO'类。 – 2009-10-14 13:49:50

+0

REwriting;)...... – 2009-10-14 13:53:50

+0

那么,首先你的代码中没有类方法。你的代码工作得很好。所以你做错了它最有可能不给我们实际的代码。 ;) – 2009-10-14 13:54:18

回答

8

as是一个不好的变量名,它是Python中的保留关键字。不要这样命名你的变量。一旦你修好了,其他的一切都会好起来的。当然,你应该做的事情:

alt_str.output() 

编辑:尝试应用output在上课的时候,我能够复制你的错误消息:AltString.output,则:AltString.output()。您应该将该方法应用于该类的实例。

alt_str = AltString('spam') 
alt_str.output() 
1

'as'和'str'是关键字,不要通过定义具有相同名称的变量来隐藏它们。

+3

'str'不是关键字,它只是一个内置类型。尽管隐藏内置是一种不好的做法,但不会造成这样的问题。 – SilentGhost 2009-10-14 13:49:25

1

您的例子是确认你在Python的预期运行2.4

>>> from x import * 
>>> as = AltString("String1") 
>>> as.append("bubu") 
>>> 
>>> as.output() 
'String1bubu' 

在Python 2.5中,也应该工作,但会提出一个有关使用的,这将成为一个Python保留关键字警告2.6。

我不明白为什么你会得到这样的错误信息。如果您使用的是Python 2.6,它可能会产生语法错误。

+0

我认为问题中显示的代码不是实际运行的代码。 – 2009-10-14 14:40:28

0

我跑到下面的代码:

class AltString: 

    def __init__(self, str = "", size = 0): 
     self._contents = str 
     self._size = size 
     self._list = [str] 

    def append(self, str): 
     self._list.append(str) 

    def output(self): 
     return "".join(self._list) 


a = AltString("String1") 

a.append("String2") 

a.append("String3") 


print a.output() 

它完美地工作。我能看到的唯一流程是使用“as”,这是一个保留关键字。

+0

'as'的使用是一个错字,因为当我尝试使用它时,我也得到了一个语法错误(我一直在使用Python 2.5.4)。 当我再次尝试使用您的示例时,一切似乎都很完美。不知道我以前做错了什么,但现在看起来好了。 :) – Trevor 2009-10-14 14:12:20

+0

@Trevor:请不要提供其他信息作为对答案的评论。请用更多信息更新问题。 – 2009-10-14 16:02:37

0

刚试过在Python 2.6.2代码和行

as = AltString("String1") 

不起作用,因为“作为”是保留关键字(见here),但如果我用另一个名字它完美的作品。