【问题标题】:Moving repetitive lines of code outside of a class for efficiency将重复的代码行移到类之外以提高效率
【发布时间】:2022-01-19 11:04:50
【问题描述】:

我已经制作了一个模块,其中有两个类如下:

class Class_1:

    def get_table(loc):
        
        ocr_xml = AbbyyXML(loc)
        xml_doc = XMLDoc(ocr_xml)
        # and some stuff
        return abc

class Class_2: 

    def get_table(loc):
        
        ocr_xml = AbbyyXML(loc)
        xml_doc = XMLDoc(ocr_xml)
        # and some stuff
         return xyz

这个想法是提供一些 .xml 文档并使用get_table() 方法进行一些操作。 这两个类都可以正常工作,我将它们应用如下:

from my_module import *
def incoming(client_name, loc):
    act = client_name.get_table(loc)
    return act

其中client_name 可以是Class_1Class_2。我的问题是关于这段代码的效率,你可以看到get_table() 方法有一个名为loc 的变量,它是.xml 文件的位置。我想知道我是否可以移动

ocr_xml = AbbyyXML(loc)
xml_doc = XMLDoc(ocr_xml)

课外避免重复?到目前为止,鉴于两个类中的方法都有变量 loc,我没有这样做并使用继承。

【问题讨论】:

  • 为什么不做一个超类,把那部分放到子类可以调用的方法中呢?
  • @h11 到目前为止我还没有使用过超类,你能用伪代码详细说明一下吗?
  • 在创建超类或子类之前,您需要检查get_table是否依赖于类变量,如果它是独立的,那么我建议只使用单独的函数,如果它是依赖的在某些类变量上,则无需创建单独的类或继承

标签: python class oop inheritance


【解决方案1】:

我实际上并没有使用过 python,但这更像是一个通用的设计问题。

在网上看了一眼,写了如下(可能编译不出来)

这是我用来参考的网站

https://www.w3schools.com/python/python_inheritance.asp

class SuperClass:
  def __init__(self):

  // put your method in here
  def readFiles(self):
    // read files and write to fields in this class

class Class_1(SuperClass):

    def get_table(loc):
        self.readFiles()
        # and some stuff
        return abc

class Class_2(SuperClass): 

    def get_table(loc):
        self.readFiles()
        
        # and some stuff
         return xyz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 2012-04-26
    • 1970-01-01
    • 2015-12-23
    • 2022-11-10
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多