【发布时间】:2022-11-13 06:39:51
【问题描述】:
我有一个类用于处理三种类型的数据结构。 在这个类中,我有许多绘图方法,这取决于加载到类中的数据类型。 在查看类属性时,有没有办法隐藏不属于加载的数据结构的方法?
例子:
class data_reader():
def __init__(self):
self.load_data()
self.data_type()
self.common_method_1()
self.common_method_2()
def load_data(self):
# Loads the data
def data_type(self):
# Figures out which of the three data structures we have
def common_method_1(self):
# A method common for all data structures
def common_method_2(self):
# Another method common for all data structures
def plot_data_1(self):
# Plotting function for data structure 1
def plot_data_2(self):
# Plot function for data structure 2
def plot_data_3(self):
# Plot function for data structure 3
if __name__ == "__main__":
a = data_reader()
a.plot_data_1()
当我检查类的方法时,我可以看到所有绘图函数。如果我加载数据结构 1,我可以隐藏其他两个绘图功能吗?
我尝试做一些内部函数,但后来它并没有成为类外的可调用方法。
感谢您的任何意见。
【问题讨论】:
-
重新考虑你的班级结构——让他们成为同一个班级真的有意义吗?将常用方法移至父类,并为每种数据类型创建一个从该父类继承的特定类。
-
根据您的评论,我查找了内部类或嵌套类,它们似乎通过添加另一个属性层来解决问题,因此:a.data1.plot() 或 a.data2.plot()。感谢您的评论!
标签: python function class methods