简体   繁体   中英

Python newbie - Understanding class functions

If you take the following simple class:

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)

And I successfully invoke the class instance using:

as = AltString("String1")

as.append("String2")

as.append("String3")

When I then invoke the output function using as.output instead of a string being returned, I get the following instead:

unbound method AltString.output

if I call it using as.output() I get the following error:

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

What I am not doing right?

as is a bad variable name, it is reserved keyword in Python. don't name your variables like this. once you fix it, everything else will be alright. of course you should be doing:

alt_str.output()

edit : I was able to replicate your error messages when trying to apply output to the class: AltString.output , then: AltString.output() . You should be applying the method to the instance of the class instead.

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

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

Your example is confirmed to work as you expect in python 2.4

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

In python 2.5 it should also work, but will raise a warning about the use of as, which will become a reserved keyword in python 2.6.

I don't really understand why you obtain such error messages. If you are using python 2.6 it should probably produce a syntax error.

I ran the following code :

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() 

And it worked perfectly. The only flow I can see is that you use "as", which is a reserved keyword.

Just tried your code in Python 2.6.2 and the line

as = AltString("String1")

doesn't work because "as" is a reserved keyword (see here ) but if I use another name it works perfectly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM