无法使用方法在python中设置类属性

sha*_*fty 5 python attributes class

初始化Foo对象确实运行方法func(),但无论如何,self.a的值都设置为None.

如何使用以下代码?

#!/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()
Run Code Online (Sandbox Code Playgroud)

输出是:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
None
None
Run Code Online (Sandbox Code Playgroud)

jte*_*ace 9

您正在重置self.a为函数的返回值.由于该函数不返回任何内容,因此该值设置为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"
Run Code Online (Sandbox Code Playgroud)