如何用super构造类实例?

时间:2018-09-19 13:54:08

标签: python constructor

我正在看这个例子

class TravellingSalesmanProblem(Annealer):

    """Test annealer with a travelling salesman problem.
    """

    # pass extra data (the distance matrix) into the constructor
    def __init__(self, state, distance_matrix):
        self.distance_matrix = distance_matrix
        super(TravellingSalesmanProblem, self).__init__(state)  # important!

simanneal克隆

如果我决定更改构造函数

def __init__(self, state, distance_matrix):
    self.state = state
    super(TravellingSalesmanProblem, self).__init__(distant_matrix)

这是Anealer类的样子

class Annealer(object):
       __metaclass__ = abc.ABCMeta

    # defaults
    Tmax = 25000.0
    Tmin = 2.5
    steps = 50000
    updates = 100
    copy_strategy = 'deepcopy'
    user_exit = False
    save_state_on_exit = False

    # placeholders
    best_state = None
    best_energy = None
    start = None

    def __init__(self, initial_state=None, load_state=None):
        if initial_state is not None:
            self.state = self.copy_state(initial_state)
        elif load_state:
            self.load_state(load_state)
        else:
            raise ValueError('No valid values supplied for neither \
            initial_state nor load_state')

        signal.signal(signal.SIGINT, self.set_user_exit)

它也有很多其他方法,但这会占用太多空间。

新的TravellingSalesmanProblem实例与上一个实例有何不同?

1 个答案:

答案 0 :(得分:3)

  

新的TravellingSalesmanProblem实例与上一个实例有何不同?

在步骤1中,您将分配状态

self.state = state

在第2步中,您需要将远距离矩阵作为参数传递给init方法

super(TravellingSalesmanProblem, self).__init__(distant_matrix)

该init方法采用第一个参数并将其解释为initial_state

self.state = self.copy_state(initial_state)

这意味着:原始状态丢失,而遥远的矩阵成为您的状态。

结论:这是一团糟。