Cannot set class attributes in python using method

Initializing the Foo object launches the func () method, but the value of self.a in any case becomes None.

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

Conclusion:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
None
None
+5
source share
2 answers

You return self.ato the return value of the function. Since the function returns nothing, the value gets the value 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"
+9
source

jterrace is correct. It happens that the func () method first prints, 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

, , __init__:, func: __main__: . , , .

+3

All Articles