shafty
shafty

Reputation: 605

Can't set class attributes in python using a method

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

Upvotes: 5

Views: 200

Answers (2)

BrewerHimself
BrewerHimself

Reputation: 123

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.

Upvotes: 3

jterrace
jterrace

Reputation: 67163

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"

Upvotes: 9

Related Questions