【问题标题】:Problem with the Property-Setter decorator: "private" attribute is not being settedProperty-Setter 装饰器的问题:未设置“私有”属性
【发布时间】:2019-07-09 03:12:05
【问题描述】:

我很难找出为什么我的自定义类 (Data_Setter_Class) 中的“Setter Decorator”不能正常工作。

我发现我的“私有”属性 (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”

感谢您抽出宝贵时间,希望尽快收到您的来信。

此致,

【问题讨论】:

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


    【解决方案1】:

    我以前也不知道这一点,但是对于您要执行的操作,带有 getter 和 setter 的“隐藏”变量的语法是 '_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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 2013-02-26
      • 2017-11-28
      • 2012-09-15
      • 2018-05-02
      • 2019-05-25
      • 2013-03-25
      相关资源
      最近更新 更多