How does a method of a subclass become a method of the base class?

Jen Kris jenkris at tutanota.com
Sun Mar 26 13:43:44 EDT 2023


The base class:


class Constraint(object):

def __init__(self, strength):
        super(Constraint, self).__init__()
        self.strength = strength

def satisfy(self, mark):
        global planner
        self.choose_method(mark)

The subclass:

class UrnaryConstraint(Constraint):

def __init__(self, v, strength):
        super(UrnaryConstraint, self).__init__(strength)
        self.my_output = v
        self.satisfied = False
        self.add_constraint()

    	def choose_method(self, mark):
        if self.my_output.mark != mark and \
           Strength.stronger(self.strength, self.my_output.walk_strength):
self.satisfied = True
        else:
            self.satisfied = False

The base class Constraint doesn’t have a "choose_method" class method, but it’s called as self.choose_method(mark) on the final line of Constraint shown above. 

My question is:  what makes "choose_method" a method of the base class, called as self.choose_method instead of UrnaryConstraint.choose_method?  Is it super(UrnaryConstraint, self).__init__(strength) or just the fact that Constraint is its base class? 

Also, this program also has a class BinaryConstraint that is also a subclass of Constraint and it also has a choose_method class method that is similar but not identical:

def choose_method(self, mark):
    if self.v1.mark == mark:
            if self.v2.mark != mark and Strength.stronger(self.strength, self.v2.walk_strength):
                self.direction = Direction.FORWARD
            else:
                self.direction = Direction.BACKWARD

When called from Constraint, it uses the one at UrnaryConstraint.  How does it know which one to use? 

Thanks,

Jen




More information about the Python-list mailing list