Python, Referencing child attributes and methods in base class (and vice versa) there has to be a better way

StackOverflow https://stackoverflow.com/questions/19755204

Question

I have a base class that is inherited by multiple child classes. This base class has a method, calc_func(self), which uses uniformly named methods, func(self), in the child classes. This works but this 'architecture' would be very hard to follow if the code ever grew more complex.

# Base class
class base():
    x = 12  
    def calc_func(self):
        for i in range(1,4):
            self.y += self.func() 
            # neither y nor func() are defined here so
            # it is hard to know where they came from


# Child class 1
class child1(base):
    y = 10
    def __init__(self):
        pass

    def func(self):   # method used in base class
        self.x += self.y
        print self.x
        return self.x
        # x was not defined here so it is
        # hard to know where it came from

# Child class 2
class child2(base):
    y = 15
    def __init__(self):
        pass

    def func(self):   # method used in base class
        self.x *= self.y
        print self.x
        return self.x
        # x was not defined here so it is
        # hard to know where it came from

test1 = child1()  # Create object
test1.calc_func() # Run method inherited from base class


test2 = child2()  # Create another object
test2.calc_func() # Run method inherited from base class

The idea was to abstract out common code to the base class but this doesn't seem to be the right way of doing it. Maybe this could be made more understandable by using a naming convention for methods and attributes which reference their particular class of origin? Maybe a different architecture altogether? Any advise will be greatly appreciated.

Was it helpful?

Solution

This base class has a method, calc_func(self), which uses uniformly named methods, func(self), in the child classes. This works but this 'architecture' would be very hard to follow if the code ever grew more complex.

No, that's exactly how object-oriented polymorphism is supposed to work. You're already doing it right!

You say that this seems difficult to understand, but it's not clear why you think it's difficult. Probably the only thing you could do is (a) mark the base class as abstract (b) have all methods that child classes are supposed to supply exist on the base class, but only have them raise NotImplementedError.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top