【问题标题】:Parent class to expose standard methods, child class to provide sub-methods to do the work父类公开标准方法,子类提供子方法做工作
【发布时间】:2019-08-07 20:32:46
【问题描述】:

我想建立一个父类,它定义了一个标准接口并为所有子实例执行通用操作。但是,对于这些方法如何完成工作,每个孩子都有不同的细节。例如,父类会提供如下标准方法:

class Camera():

    camera_type = None

    def __init__(self, save_to=None):
        self.file_loc = save_to

    def connect(self):
        self.cam_connect()
        with open(self.file_loc, 'w'):
            # do something common to all cameras


    def start_record(self):
        self.cam_start_record()
        # do something common to all cameras

这些方法中的每一个都引用另一个仅位于子级中的方法。子类将具有有关如何执行所需任务的实际详细信息,其中可能包括几种方法的组合。例如:

class AmazingCamera(Camera):

    camera_type = 'Amazing Camera'

    def __init__(self, host_ip='10.10.10.10', **kwargs):
        super(AmazingCamera, self).__init__(**kwargs)

        self.host_ip = host_ip

    def cam_connect(self):
        print('I are connectifying to {}'.format(self.host_ip))
        # do a bunch of custom things including calling other 
        # local methods to get the job done.

    def cam_start_record(self):
        print('Recording from {}'.format(self.host_ip)
        # do a bunch more things specific to this camera

### etc...

上面的结果提供了一个接口如:

mycamera = AmazingCamera(host_ip='1.2.3.4', save_to='/tmp/asdf')
mycamera.connect()
mycamera.start_record()

我完全理解我可以简单地覆盖父方法,但是在父方法执行其他操作(例如处理文件等)的情况下,我宁愿不必这样做。到目前为止,我上面的内容似乎工作得很好,但在我继续创建它之前,我想知道是否有更好、更 Python 的方式来实现我所追求的。

TIA!

【问题讨论】:

  • AmazingCamera.start_record() 中,您可以先调用super().start_record(),然后继续使用您的AmazingCamera 代码。
  • 你有的很好。
  • 谢谢大家。两种方法都运作良好。我决定走 super() 路线。

标签: python-3.x class inheritance


【解决方案1】:

我选择在父子节点之间保持标准方法相同,并尽量减少子节点特定辅助方法的使用。只是看起来更干净。

举个例子:

class Camera():

    camera_type = None

    def connect(self):
        with open(self.file_loc, 'w'):
            # do something common to all cameras

然后在孩子中我覆盖了方法,但在覆盖中调用父级的方法如下:

class AmazingCamera(Camera):

    camera_type = 'Amazing Camera'

    def cam_connect(self):
        print('I are connectifying to {}'.format(self.host_ip))

        # call the parent's method
        super().connect()

        # do a bunch of custom things specific to
        # AmazingCamera

【讨论】:

    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2016-02-14
    • 1970-01-01
    • 2011-09-04
    • 2012-02-22
    相关资源
    最近更新 更多