user5745186
user5745186

Reputation:

While evaluating length of a list that is defined as a class

For example, I got a class named stack,

class stack: #Will be used for probable files!
    def __init__(self):
            self.data = []

    def add(self, element):
            self.data.append(element)

    def number_of_elements(self):
            return len(self.data)

    def stackType(self):
        if self.number_of_elements == 0:
            return 0
        elif self.number_of_elements == 1:
            return 1
        else:
            return -1

I then do this:

foo = stack()
print foo.stackType()

I get -1 however I was expecting a return of 1

Why is it so and how can I handle with it?

Upvotes: 1

Views: 34

Answers (3)

mhawke
mhawke

Reputation: 87134

That's because you did not call the call the method self.number_of_elements; you merely tested to see if it equalled 0 or 1.

Modify your code to actually call the method using this syntax: self.number_of_elements() [notice the use of () to call the method]:

def stackType(self) :
        if self.number_of_elements() == 0 :
                return 0
        elif self.number_of_elements() == 1 :
                return 1
        else :
                return -1

You could also have written it like this:

def stack_type(self):
    n = self.number_of_elements()
    return -1 if n > 1 else n

which would be an improvement because number_of_elements() will be called once only. In your code the method could be called twice. I renamed the function to be consistent with the Python method naming conventions set out in PEP8.

Upvotes: 3

Jon Kiparsky
Jon Kiparsky

Reputation: 7753

self.number_of_elements is a function, so its value is neither zero nor 1

Upvotes: 0

holroy
holroy

Reputation: 3127

Because self.number_of_elements is not the same as self.number_of_elements()!

The former is a reference to the function, the latter is a call to the function actually calculating the length of your stack.

Upvotes: 1

Related Questions