首页 > 解决方案 > 如何从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)    

预期输出: 你好阿尔伯特!

任何想法,然后请!谢谢。

标签: pythonoop

解决方案


您在类中定义类变量:

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通常在类上调用,因此应该假定第一个参数是类。


推荐阅读