gpt4 book ai didi

python-3.x - Python静态方法定义放置

转载 作者:行者123 更新时间:2023-12-05 07:16:14 24 4
gpt4 key购买 nike

我正在寻找一种约定,说明如何安排 Python 类定义中不同类型的方法(即 @staticmethod@classmethod)。 PEP-8不提供有关此类主题的任何信息。

例如,Java 编程语言有一些code conventions指的是静态变量和实例变量出现在类定义 block 中的顺序。 Python 3 是否有任何标准声明此类建议?

最佳答案

到目前为止缺乏答案只是促使我简单地写下我的做法:

class thing(object):

info = 'someinfo'
# this can be useful to provide information about the class,
# either as text or otherwise, in case you have multiple similar
# but different classes.
# It's also useful if there are some fixed numbers defining
# the class' behaviour but you don't want to bury them somewhere
# in the code (and haven't gotten around to putting them into
# a separate file or look-up table, as you probably should)

@staticmethod
def stat(arg1, arg2):
'''similarly, static methods are for stuff that is specific
to the class but still useful without an instance'''
pass
# e.g.: some preprocessor for input needed to instantiate the class, or a computation specific to the type of thing represented by the class
return(arg1 + arg2)

@classmethod
def classy(cls, str1)
'''class methods get access to other class stuff. So, basically,
they can do less-trivial things'''
return(cls.stat(str1, cls.info)

def __init__(self, arg):
# ...and here starts the regular class-internal stuff
self.arg = arg

def simplething(self, arg):
'''I like to put the simple things first which don't call
other instance methods...'''
return(arg * self.arg)

def complicated(self, arg1, arg2):
'''...before the methods which call the other methods above them'''
return(self.simplething(arg1) / simplething(arg2))

简而言之:在创建类之前任何有用的东西都在 __init__() 定义之上,首先是类全局定义,然后是静态方法,然后是类方法,然后是 >__init__(),所有方法按层次顺序排列。

这样做的好处(对我来说)是,当我滚动代码并找到某个调用类中其他方法的方法时,我已经看到了那些方法。我想没有客观的“最佳”方法可以做到这一点,因为您也可以反过来安排事情,并且仍然知道先看哪里。对我来说,这种方式对我来说更直观。它还具有优势,在开发过程中的某个时刻,我更有可能在底部添加更高级别的方法,而不是将低级别的方法挤在顶部。

另一种方法可能是按“相关性”对事物进行排序。即:该类的用户最常需要的东西可能位于顶部。如果您有很多人使用您的代码但不修改它(很多),那可能会很好。我确实看到有些人不是以这种方式组织他们的类,而是组织函数模块:您最有可能直接调用的函数在顶部,它调用的函数在下面。但是对于一个方法很少按顺序执行的类的内部结构,这种顺序可能很难确定,并且可能更难找到静态或类方法的明确列表。

...绝对不是标准,但对于那些正在寻找它的人来说可能有点方向,或者至少是一个起点来解释为什么你的订单比我的好:)

关于python-3.x - Python静态方法定义放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com