gpt4 book ai didi

python - 类设计: methods that share a lot of the same code

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:59 26 4
gpt4 key购买 nike

此时我想创建一个有两个方法的类(我也希望能够明显地改变类(class))。

class ogrGeo(object):

def __init__(self):
pass

def CreateLine(self, o_file, xy):
#lots of code


def CreatePoint(self, o_file, xy):
# lot's of the same code as CreateLine(),
# only minor differences

保持事物干净并重复尽可能少的代码我正在寻求一些建议。这两个方法 CreateLine()CreatePoint() 共享很多代码。减少冗余:是否应该定义两种方法都可以调用的第三种方法?在这种情况下你仍然可以打电话 o = ogrGeo()
o.CreateLine(...)
o.CreatePoint(...)
分开。还是应该将它们合并为一种方法?是否还有其他我没有考虑过或一无所知的解决方案?

已经感谢您的任何建议。

最佳答案

是否应该将这些方法合并为一个是 API 设计的问题。如果这些功能有不同的用途,那么您可以将它们分开。如果客户端代码可能遵循该模式,我合并它们

if some_condition:
o.CreateLine(f, xy)
else:
o.CreatePoint(f, xy)

但除此之外,不要合并。相反,将公共(public)代码重构为私有(private)方法,如果公共(public)代码不涉及 self,甚至重构为独立函数。 Python 在语言中没有内置“私有(private)方法”的概念,但是以 _ 开头的名称将被识别为私有(private)方法。

关于python - 类设计: methods that share a lot of the same code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530780/

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