python - 如何从Python中的自定义导入文件访问嵌套@classmethod中的变量?
问题描述
让我们考虑以下代码,
实际文件
[test.py]
from util.rx import RX
msg = RX.get_msg('Albert!')
print(msg)
实用程序类文件
[rx.py]
class RX(object):
def __init__(self):
self.data = 'Hello ' # How to define this var? (self.data or cls.data)
@classmethod
def msg(cls, name):
return self.data + name
# Shall I use "@staticmethod" in below? If once yes, then how to call the another
# method inside the same class? (i.e, without 'self' or 'cls')
@classmethod
def get_msg(cls, name = None):
return cls.msg(name)
预期输出: 你好阿尔伯特!
任何想法,然后请!谢谢。
解决方案
您在类中定义类变量:
class RX(object):
data = 'Hello ' # here
@classmethod
def msg(cls, name):
return cls.data + name
@classmethod
def get_msg(cls, name=None):
return cls.msg(name)
并且classmethods
通常在类上调用,因此应该假定第一个参数是类。
推荐阅读
- python - Facebook sdk python在没有登录的情况下输出访问令牌?
- vba - 是否为空返回“”
- python - 可视化 CNN 过滤器时,元组索引超出范围
- vue.js - 如何从 getPlaceDetails 获取照片位置?在 VUE 中
- python - 无法在 QTreeWidget 中添加 QTextEdit
- clojure - 你在 lisp 中看到的最优雅的一段代码是什么
- javascript - 使用具有内容类型的 POST Fetch 调用时,从服务器返回本机 422 Unprocessable Entity 错误:application/x-www-form-urlencoded
- r - R:sparklyr 中的组(“sum”、“count distinct”、“mean”)
- javascript - JS中的评论是如何分类的?
- python - 在 Python 中使用 XLwings 从下拉列表中选择