如何使用实例变量在python中声明类变量?

问题描述

我想知道如何使用实例变量创建类变量。 例如,

class Myclass:
     def __init__(self,data):
         self.data=data
     current_data=self.data  # here I got an error since we cannot use self

Ps:我需要 current_data 是一个变量,而不是一个函数。事实上,我可以做到这一点,但我想要另一种方法

def curren_data(self):
    return self.data

谢谢。

解决方法

我同意这样的评论,即它似乎没有多大意义,因为我们不知道您为什么要这样做。 除此之外,我认为您只需在构造函数中设置 current_data 即可使其工作,如下所示:

class MyClass:
    def __init__(self,data):
        self.data=data
        MyClass.current_data=self.data

除了在构造函数中设置之外,您还可以通过函数进行设置。