У меня серьезные трудности с выяснением, почему мой «Setter Decorator» из моего пользовательского класса (Data_Setter_Class) не работает должным образом.
Я обнаружил, что мой «Приватный» атрибут (self .__ Data) не был правильно настроен моим декорированным методом (self.Data).
Поэтому, как только я создаю экземпляр класса «Data_Setter_Class» и пытаюсь получить доступ к его атрибуту Data с помощью метода декоратора его свойств, я получаю сообщение о том, что у моего класса просто нет атрибута «__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 '
Я благодарю вас за ваше время и надеюсь услышать от вас скоро.
С уважением,