首页 > 解决方案 > 在类中调用函数并在另一个函数中使用结果

问题描述

class myclass():
    def fun(self):
        a = 12
        return a

    b = fun()

TypeError: fun() missing 1 required positional argument: 'self'

这个想法是能够b在另一个内部使用def,比如

class myclass():
    def fun(self):
        a = 1
        return a

    b = fun()

    def fun2(self):
        c = self.b + 2

这可能吗?

标签: pythonfunctionclass

解决方案


因为myclass.fun它是一个实例方法,如果你想缓存它的结果,你应该在实例属性(定义在 中__init__)而不是类属性中这样做。

class myclass():
    def __init__(self):
        self.b = self.fun()

    def fun(self):
        a = 1
        return a

    def fun2(self):
        c = self.b + 2

推荐阅读