【发布时间】:2018-02-24 11:14:31
【问题描述】:
长话短说,我需要编写一个主要使用 OOP 原则的数据分析工具。我不是 python 的初学者,但仍然不是最好的。我写了一个函数,它根据用户输入的内容返回真或假值(如下):
def secondary_selection():
"""This prints the options the user has to manipulate the data"""
print("---------------------------")
print("Column Statistics [C]")
print("Graph Plotting [G]")
d = input(str("Please select how you want the data to be processed:")).lower()
# Returns as a true/false boolean as it's easier
if d == "c":
return True
elif d == "g":
return False
else:
print("Please enter a valid input")
此函数按我想要的方式工作,但我随后尝试将其导入到不同的文件中以与类一起使用(如下):
class Newcastle:
def __init__(self, data, key_typed):
self.data = data[0]
self.key_typed = key_typed
def newcastle_selection(self):
# If function returns True
if self:
column_manipulation()
# If function returns False
if not self:
graph_plotting()
newcastle_selection(self) 函数将secondary_selection() 函数作为参数,但我让它工作的唯一方法是if self 语句。写if true 之类的东西会导致column_manipulation 和graph_plotting 函数被打印。
我想知道是否有更好的方法来编写这个,因为我不是 python 的初学者,但对它还是比较陌生。
免责声明:这是第一年的课程,我最后问了这个结果。
【问题讨论】:
-
能否请您修复问题中代码的缩进。因为它是我们无法说出代码的确切结构。
-
应该没有
if self。自我总是在那里,它是一个隐含的论点。你不应该自己通过。除非您希望该函数成为staticmethod,否则请保留 self 并为您传递给newcastle_selection的任何内容添加一个额外的参数。 -
@PaulRooney 所以我应该写类似
newcastle_selection(self, x)这样的东西if x == True而不是if self: -
您的代码与您对它的描述不匹配,“
newcastle_selection(self)函数将secondary_selection()函数作为参数”。我是否忘记了如何在夜间阅读 Python,或者我们可以确定这在您的代码中不正确? -
我不确定
if self这样的代码在OOPS中是否有意义。重点是self在那里,并且函数是从self的上下文中调用的:-) 或者换句话说,class函数是从objects的上下文中调用的。我喜欢将class视为具有state和behaviour。
标签: python python-3.x oop