Roadhouse
Roadhouse

Reputation: 197

Can't access lists within objects in Python

I have a simple application in which I want to be able to add texts organized in texts, sentences and tokens. Each text contains a number of sentences, and each sentence contains a number of tokens. My classes look like this:

class Text:
    sentences = []

    def __init__(self, meta):
        self.meta = meta

    def getSentences(self):
        return self.sentences

    def addSentence(self, s):
        self.sentences.append(s)

class Sentence:
    tokens = []

    def __init__(self):
        pass

    def getTokens(self):
        return self.tokens

    def addToken(self, t):
        self.tokens.append(t)

class Token:
    def __init__(self, word, pos):
        self.word = word
        self.pos = pos

    def getWord(self):
        return self.word

    def getpos(self):
        return self.pos

I then create a token, a sentence and a text like this:

token = Token("a", "b")
sent = Sentence()
sent.addToken(token)
txt = Text("meta")
txt.addSentence(sent)

Now, when I want to access that token, i.e. the first token of the first sentence of the first text, I want to be able to do something like this:

print txt.getSentences[0].getTokens[0]

... which doesn't work at all. I can access the getSentences method like this

 print txt.getSentences

which gives me this

 <bound method Text.getSentences of <txt.Text instance at 0x1006d5a70>>

Upvotes: 3

Views: 1139

Answers (3)

Copperfield
Copperfield

Reputation: 8510

As additional note: to give yours class the behavior of MyInstance[0], like with list, you have to define the special method

__getitem__

Upvotes: 0

Alex Volkov
Alex Volkov

Reputation: 2962

You have two issues with your code.

First, you are defining sentences and tokens as class variables

>>> class Test:
...     myvar = []
... 
>>> 
>>> t1 = Test()
>>> t1.myvar.append(10)
[10]
>>> t2 = Test()
>>> print(t2.myvar)
[10]

You should initialize these variables in __init__

Second, in python functions are called with () operator, just referring to a function name returns function object.

>>> def myfunc():
...     print("hello,world!")
... 
>>> yourfunc = myfunc
>>> yourfunc()
hello,world!

In the case of using variable sentences you can access it directly with txt.sentences, there's no private/public method distinction in python, well there are names with _-under and __-dunder prefixes, but that's convention.

Upvotes: 3

Destruktor
Destruktor

Reputation: 463

Try this:

print txt.getSentences()[0].getTokens()[0]

This should return the lists instead of the methods.

Upvotes: 0

Related Questions