Pythonic方法来封装类的方法参数

时间:2017-11-24 09:56:51

标签: python oop inheritance encapsulation

我的类A的对象类似于网络连接,即以每个连接打开的句柄为特征。也就是说,使用句柄(特定连接)作为参数调用不同的方法。我的A类(python 2.7)看起来像:

const db = {};
exports.get = function (id) {
    console.log('Getting task ' + id);
    return {
        name: 'new task from db'
    };
};
exports.save = function (task) {
    console.log('Saving ' + task.name + ' to the db');
};
console.log('newing up task repo');

典型用法是

class A(object):
  def __init__(self, *args):
    ... some init
  def my_open(self, *args)
    handle = ... some open
    return handle
  def do_this(self, handle, *args):
    foo_this(handle, args)
  def do_that(self, handle, *args):
    foo_that(handle, args)

现在,在特定情况下,只有一个连接需要处理,即一个游戏中的句柄。因此,隐藏此句柄是合理的,但在更一般的情况下保持A类。因此,我对B级的第一个想法 其中"是"类A(用法保持不变但隐藏处理)是:

a = A(args)
handle = a.my_open(args2)
a.do_this(handle, args3)

不幸的是,在我看来,它似乎非常复杂。有更好的想法吗?

2 个答案:

答案 0 :(得分:1)

  

我的类A的对象类似于网络连接,即以每个连接打开的句柄为特征。也就是说,使用句柄(特定连接)作为参数调用不同的方法。

你已经倒转了责任。 handle对象保存方法操作的状态,因此这些方法应该存在于句柄上,而不是工厂。

将方法移动到handle对象,因此API变为:

a = A(args)
handle = a.my_open(args2)
handle.do_this(args3)

如果需要,实施handle()的班级可以保留对a的引用;这是API用户无需担心的实现细节。

然后根据需要返回新句柄,单句柄。

通过将责任转移到handle对象,您还可以根据参数使工厂生成完全不同类型的句柄。例如,A(args).my_open(args2)也可以生成您现在拥有类B的单例句柄。

答案 1 :(得分:0)

handle本身的课程怎么样?:

class Handle(object):
    def __init__(self, *args):
        # init ...
        self._handle = low_level_handle
    def do_this(self, *args):
        # do_this ...
        pass
    def do_that(self, *args):
        # do_that
        pass

class A(object):
    def __init__(self, *args):
       # init ...
    def my_open(self, *args):
       handle = Handle(args)
       # handle post-processing (if any)
       return handle

e.g:

a = A(args)
handle = a.my_open(args2)
handle.do_this(args3)