python-3.x - Property-Setter 装饰器的问题:未设置“私有”属性
问题描述
我很难找出为什么我的自定义类(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”
感谢您抽出宝贵时间,我希望尽快收到您的来信。
您忠诚的,
解决方案
我以前也不知道这一点,但是对于您要执行的操作,带有 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
推荐阅读
- javascript - 在 vue 中删除列表中的对象时出错
- python-3.x - 计算从 PE 调用每个 IAT 的次数
- php - update_option 到 for 循环中的数组
- powershell - Start-Job - 参数的位置顺序
- php - 使用 PHP 和 PDO 搜索表单,然后在页面上显示结果
- java - 重新格式化字符串数组
- asp.net - VB.NET - 单击 DataGridView 超链接并获取单击的文本
- reporting-services - 堆叠条形图中的 SSRS 匹配颜色系列
- database - Codeigniter SUM 查询只带来一行
- jquery - 如果模态已打开,则不要进行位置重新加载