5

Initialising the Foo object does run the method func(), but the value of self.a gets set to None anyway.

How can I get the following code to work?

#!/usr/bin/env python

class Foo(object):

    def __init__(self, num):
        self.a = self.func(num)
        print self.a

    def func(self, num):
        self.a = range(num)
        print self.a

    def __str__(self):
        return str(self.a)


def main():
    f = Foo(20)
    print f

if __name__ == "__main__":
    main()

The output is:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
None
None
1
  • You don't have any class attributes, only instance attributes. Commented Jul 4, 2012 at 20:52

2 Answers 2

9

You're resetting self.a to the return value of the function. Since the function returns nothing, the value gets set to None.

def __init__(self, num):
    self.a = self.func(num)  # return value of function is None
    print self.a             # self.a is now None

def func(self, num):
    self.a = range(num)      # sets self.a to [0..19]
    print self.a             # prints [0..19]
    # implicit "return None"
Sign up to request clarification or add additional context in comments.

Comments

3

jterrace is correct. What's happening is that the func() method is printing first, not the init method. Consider this program:

#!/usr/bin/env python

class Foo(object):

    def __init__(self, num):
        self.a = self.func(num)
        print '__init__:', self.a

    def func(self, num):
        self.a = range(num)
        print 'func:', self.a

    def __str__(self):
        return str(self.a)

if __name__ == '__main__':
    f = Foo(20)
    print '__main__:', f

It's very similar to yours except I added __init__:, func:, and __main__: to the respective function's print statements. Run this and you should have a better understanding of what's going on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.