python - Two classes with a structurally identical method but one differently named variable -


i have 2 classes common function f, here:

class classa(object):      def f(self, var):         self.a = g(var, self.a)      # specific code classa, changing self.a  class classb(object):      def f(self, var):         self.b = g(var, self.b)      # specific code classb, changing self.b 

in both classes, f same on 2 variables called a , b, structurally equivalent. put f abstract class avoid code duplication. 1 way is

class classx(object):      def f(self, var):         self.x = g(var, self.x)  class classa(classx):      # specific code classa, changing self.x  class classb(classx):      # specific code classb, changing self.x 

in solution variables a , b have been renamed x. however, make code more self-explaining, keep specific names (say a,b) x in special classes.

is there way this?

also please comment if can suggest more meaningful , descriptive title, becomes more valuable community.

edit: solution should work if variables a, b take type pass-by-value , should assume both value , type might changed outside class during program execution.

first, caveat: if case calls inheritance of kind describe, variable name should same. in cases, giving different names attributes identical in 2 related classes doesn't make code more self-explaining -- makes less self-explaining. makes attributes different when they're same, adding complexity , potential confusion.

however, can imagine few cases might want -- sounds bit want define common interface 2 different kinds of objects. 1 simple approach use properties define aliases; in each class, you'd have different attributes (a , b), you'd define property, x, access appropriate attribute in either case. in classa, you'd in class definition:

@property def x(self):     return self.a @x.setter def x(self, value):     self.a = value @x.deleter def x(self):     del self.a 

and in classb:

@property def x(self):     return self.b @x.setter def x(self, value):     self.b = value @x.deleter def x(self):     del self.b 

then, define common function work x, subclasses inherit, overriding property x in whatever way appropriate.

this rarely worth additional layer of indirection though. of time, if there's reason 2 classes share method, should share attributes method changes, name , all.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -