zheyuanWang
zheyuanWang

Reputation: 1374

How to share class methods between classes?

The methods, which are used for debugging, rely on some class attributes. So in the original version, they are written as private class methods in each class. The code is repeated.

class Network1(NetworkTemplate):
  def __init__(self, model_config)
    self.parameter = model_config

  def __debug_tool(self):
    # repeated code
    return self.parameter


class Network2(NetworkTemplate):
  def __init__(self, model_config)
    self.parameter = model_config

  def __debug_tool(self):
    # repeated code
    return self.parameter

I am wondering how I could reuse the repeated code.

I thought of import __debug_tool but it depends on some class attributes self.parameter. I don't know if I should manually pass 6 parameters to the imported function, because it looks ugly.

Writing it in the NetworkTemplate as a public method seems the right thing to do, but I am not sure if it will impact the normal performance (i.e. with the debug tools turned off, or committed out, in the Network1).

Upvotes: 0

Views: 416

Answers (1)

mkrieger1
mkrieger1

Reputation: 23151

Writing __debug_tool as a method of the NetworkTemplate class will provide it to the derived Network1 and Network2 classes by inheritance and will not affect the performance.

When doing so, you must not use a name beginning with two underscores, because this is specifically intended to mangle the name (in order to prevent it from being overwritten accidentally by a derived class) and you will not be able to access it in Network1 and Network2.

So pick a name with one or zero leading underscores (_debug_tool or debug_tool).

See for example What is the meaning of single and double underscore before an object name? for more details.

Upvotes: 2

Related Questions