Property-Setter装饰器出现问题:未设置“私有”属性

时间:2019-02-15 01:24:13

标签: python-3.x class object methods python-decorators

我要认真弄​​清楚为什么自定义类(Data_Setter_Class)中的“ Setter装饰器”无法正常工作。

我发现我的“装饰”属性(self.Data)未正确设置“私人”属性(self .__ Data)。

因此,一旦我实例化了“ Data_Setter_Class”,并尝试通过其属性装饰器方法访问其Data属性,就会收到一条错误消息,指出我的类根本没有“ __Data”属性。

我的自定义类的描述:这是一个类,应根据一些已制定的规则(数据对象的类型,数据维度...)来测试我的数据的结构。

我正在使用的Python版本:3.6.4

代码如下:


import pandas as pd
import numpy as np
import geopandas as gpd


class Data_Setter_Class(object):
    def __init__(self, Data):
        """

        This Class allows one to evaluate the best probability distribution function (PDF), \
        and its relative best parameters for the given Series (array).


        """
        self.Data = Data


    @property
    def Data(self):
        print("\n\n\tEis os Dados\n\n")
        return self.__Data

    @Data.setter
    def Data(self, data_entry):

        print("Iniciando a análise dos dados inseridos")
        print("Eis o cabeçalho deles: \n\n", data_entry.head(), '\n\n')

        if isinstance(data_entry, np.ndarray) and np.ndim(data_entry) >1:
            Chosen_Dimension = int(input("The data has more than one dimension (1D). \
                                         Choose what dimension the distribution fit analysis should be applyed: \n\n "))

            self.__Data = data_entry[Chosen_Dimension]


        elif isinstance(data_entry, pd.DataFrame):
            if np.ndim(data_entry) >2:

                Chosen_Dimension = input("The data has more than one dimension (1D). \
                                         Choose what dimension the distribution fit analysis should be applyed: \
                                         \n\n {0} \n\n".format(data_entry.keys()) )

                while Chosen_Dimension not in data_entry.keys():
                    print("Dimension not properly set. Choose between the options given!")

                    Chosen_Dimension =input("Choose what dimension the distribution fit analysis should be applyed: \n\n {0} \n\n".format( self.data_entry.keys() ) )

                print("Dimension/Attribute Selected: ", Chosen_Dimension)

                self.__Data = data_entry.loc[:,Chosen_Dimension]

                self.Chosen_Dimension = Chosen_Dimension


        elif isinstance(data_entry, gpd.GeoDataFrame):
            if np.ndim(data_entry) >2:

                Chosen_Dimension = input("The data has more than one dimension (1D). \
                                         Choose what dimension the distribution fit analysis should be applyed: \
                                         \n\n {0} \n\n".format(data_entry.keys()) )

                while Chosen_Dimension not in data_entry.keys():
                    print("Dimension not properly set. Choose between the options given!")

                    Chosen_Dimension =input("Choose what dimension the distribution fit analysis should be applyed: \n\n {0} \n\n".format( self.data_entry.keys() ) )

                print("Dimension/Attribute Selected: ", Chosen_Dimension)

                self.__Data = data_entry.loc[:,Chosen_Dimension]

                self.Chosen_Dimension = Chosen_Dimension



        elif isinstance(data_entry, pd.Series):

            self.__Data = data_entry


        elif isinstance(data_entry, np.ndarray):
            if np.ndim(data_entry) ==1:
                self.__Data = data_entry


        elif isinstance(data_entry, np.array):
            if np.ndim(data_entry) ==1:
                self.__Data = data_entry


        else:
            try:
                self.__Data = np.array(data_entry)

            except:
                print("Data Format out of order. Try setting it up to 1D array object like before applying to the Best Fit Distribution Function")



        print("Eis o data_entry após todo o teste de dados: \n\n", data_entry.head(), '\n\n')



    @property
    def Chosen_Dimension(self):
        print("This is the numerical attribute selected for the analysis: ", str(self.__Chosen_Dimension))

        return self.__Chosen_Dimension


    @Chosen_Dimension.setter
    def Chosen_Dimension(self, chosen_dimension):

        self.__Chosen_Dimension = chosen_dimension


if "__main__" == __name__:


    Temporal_data = pd.date_range(start='1995/12/31', end='2000/12/31', freq='D')
    Size = Temporal_data.size 

    Random_Array = pd.DataFrame({'Precipitacao': np.random.randint(low=0, high=350, size=Size)}, 
                                index=Temporal_data)



    Data_Setter_Object = Data_Setter_Class(Data=Random_Array)

    Random_Array = Data_Setter_Object.Data




出现的消息错误:

AttributeError:“ Data_Setter_Class”对象没有属性“ _Data_Setter_Class__Data”

感谢您的宝贵时间,希望很快能收到您的来信。

真诚的,

1 个答案:

答案 0 :(得分:0)

我以前也不知道这一点,但是对于您要尝试执行的操作,带有getter和setter的“ hidden”变量的语法是'_var_name'而不是'__var_name'。将您的__init__方法更改为此。

def __init__(self, Data):
    """

    This Class allows one to evaluate the best probability distribution function (PDF), \
    and its relative best parameters for the given Series (array).


    """
    self._Data = Data

以及类似@property和@ Data.setter方法中的变量称为self._Data而不是self .__ Data

使用此示例的其他问题的示例: Using Property Setter In __init__

文档:https://docs.python.org/3/library/functions.html#property