【问题标题】:call function inside class and use the result in another function在类中调用函数并在另一个函数中使用结果
【发布时间】:2021-04-01 01:48:08
【问题描述】:
class myclass():
    def fun(self):
        a = 12
        return a

    b = fun()

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

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

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

    b = fun()

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

这可能吗?

【问题讨论】:

  • def fun2(self): c = self.fun() + 2?还是您想确保只调用一次fun
  • 我不明白你为什么还需要b

标签: python function class


【解决方案1】:

由于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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多