python - 在类中调用函数并在另一个函数中使用结果
问题描述
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
这可能吗?
解决方案
因为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
推荐阅读
- r - 有没有办法使代码/注释中的超链接不可点击?
- spring-boot - RedisCustomConversions 使用 Redis 存储库
- python - python:用另一种实现模拟一个类
- javascript - 使用localStorage刷新页面后如何保持按钮切换?
- python - 在多索引熊猫数据帧上应用函数
- laravel - laravel:检查我的数据库中的现有记录
- git - 删除最高级别的 git 存储库,保留较低级别
- blender - 在完成的搅拌机绘图上更改场景单位
- flask-sqlalchemy - 无法为我的视图创建模型,缺少属性“c”
- python - 发送多行以使用 pandas