【问题标题】:Is this pythonic? Class self variable这是pythonic吗?类自变量
【发布时间】: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_manipulationgraph_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 视为具有statebehaviour

标签: python python-3.x oop


【解决方案1】:

我不确定我是否真的很好地理解了您的代码结构,但看起来factory 可以帮助您:

def column_manipulation():
    print("Column manipulation")


def graph_plotting():
    print("Graph plotting")


class Newcastle:
    def __init__(self, data, func):
        self.data = data[0]
        self._func = func

    def newcastle_selection(self):
        return self._func()

    @classmethod
    def factorize(cls, data, key_typed):
        if key_typed is True:
            return cls(data, column_manipulation)
        elif key_typed is False:
            return cls(data, graph_plotting)
        else:
            raise TypeError('Newcastle.factorize expects bool, {} given'.format(
                type(key_typed).__name__
            ))


nc = Newcastle.factorize(["foo"], True)
nc.newcastle_selection()

nc = Newcastle.factorize(["foo"], False)
nc.newcastle_selection()

输出

Column manipulation
Graph plotting

主要思想是以通用方式定义您的类,因此您将function 作为__init__ 参数存储在self._func 中,然后在newcastle_selection 中调用它。

然后,您创建一个classmethod 来获取您的数据和key_typed。该方法负责选择当前实例使用哪个函数(column_manipulationgraph_plotting)。

因此,您不必在类中存储诸如 key_typed 之类的无用值,也不必处处处理特定情况,仅在 factorize 中处理。

我认为更清洁和强大(顺便说一句,它回答了你的问题“这是pythonic”,这是)。

【讨论】:

  • 这更干净@jszabo
【解决方案2】:

这是使用类的 secondary_selection 方法的简单基本示例。这可能会有所帮助。

class castle:
    def __init__(self):
        self.data = ''

    def get_input(self):
        print("1: Column Statistics")
        print("2: Graph Plotting")
        self.data = input("Please select how you want the data to be processed: ")

    def process(self):
        if self.data == 1:
            return self.column_manipulation()
        else:
            return self.graph_plotting()

    def column_manipulation(self):
        return True

    def graph_plotting(self):
        return False


c = castle()
c.get_input()
result = c.process()
print(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多