使用Python中的方法在__init__中设置属性?

问题描述 投票:0回答:1

我正在学习Python。我希望在创建该类的对象时将

self.characteristic
设置为 5。我使用的是
set.characteristic
方法,因为实际上需要进行大量计算才能达到值 5。我希望下面代码的输出为 5,但我没有得到任何结果。为什么?谢谢!

class AnyClass:

    def __init__(self):
        self.characteristic = self.set_characteristic()


    def set_characteristic(self):
        # in reality would do a bunch of calculations 
        self.characteristic = 5


obj = AnyClass()
print(obj.characteristic)

# Output: None 
# Expected output: 5
python class attributes
1个回答
0
投票

您忘记了

return
函数中所需的值。

def set_characteristic(self):
    # in reality would do a bunch of calculations 
    return 5

当不返回值时,函数返回

None

© www.soinside.com 2019 - 2024. All rights reserved.