python-3.x - Python从相同的类方法调用类属性
问题描述
我有类方法wait_for_operation,我想从中调用类属性并生成一个我想与类方法一起使用的新客户端。
def get_new_bearer_token():
return "new_token"
class MyClass(object):
def __init__(self, json):
self.json = json
@property
def client(self):
k8_loader = kube_config.KubeConfigLoader(self.json)
call_config = type.__call__(Configuration)
k8_loader.load_and_set(call_config)
Configuration.set_default(call_config)
return client
@classmethod
def wait_for_operation(self, kube_config, cloud):
while True:
if cloud == "AWS":
kube_config['users'][0]['user']['token'] = get_new_bearer_token()
self.json = kube_config
#call class property to generate a new client with token and use it
if __name__ == '__main__':
kube_config = {}
my_client = MyClass(json=kube_config)
my_client.client.CoreV1Api().list_namespace(watch=False)
result = MyClass.wait_for_operation(kube_config=kube_config,cloud='AWS')
解决方案
使用改变状态或具有副作用的属性是一个非常糟糕的主意。属性旨在表示实例数据的视图,这就是为什么我们不真正说“调用属性”,而是“获取或设置属性”。
我的建议 - 删除@property
装饰器并制作client
成普通方法。给它一个更好的名字,比如generate_new_client
. 然后像任何其他方法一样调用它 - self.generate_new_client()
.
推荐阅读
- javascript - 在 Promise 的存储桶中获取所有 Amazon S3 文件
- gradle - 阿帕奇骆驼石英2没有运行
- c - 无法在 Ubuntu 中运行已编译的文件
- asp.net - ASP.NET Core 在 Internet 上不可用
- java - 无法在 Java Web 项目 Netbeans 12.4 上加载或 js
- spring-boot - 连接表并返回数据以与 Spring JPA 做出反应
- database - 解析上的 Flutter CRUD 数据库操作 - Back4app
- three.js - 在three.js中创建具有平底的锥形几何?
- python - 如何获取两个 yyyy-mm-dd 日期之间的整数天数
- java - BeanUtils.copy 不起作用 - 错误非空属性引用空值或瞬态值