On 2023-03-26 19:43:44 +0200, Jen Kris via Python-list wrote: > The base class: > > > class Constraint(object): [...] > def satisfy(self, mark): > global planner > self.choose_method(mark) > > The subclass: > > class UrnaryConstraint(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,
Nothing. choose_method isn't 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? This works only if satisfy() is called on a subclass of Constraint which actually implements this method. If you do something like x = UrnaryConstraint() x.satisfy(whatever) Then x is a member of class UrnaryConstraint and will have a choose_method() method which can be called. > 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: ... > When called from Constraint, it uses the one at UrnaryConstraint. How > does it know which one to use? By inspecting self. If you call x.satisfy() on an object of class UrnaryConstraint, then self.choose_method will be the choose_method from UrnaryConstraint. If you call it on an object of class BinaryConstraint, then self.choose_method will be the choose_method from BinaryConstraint. hp PS: Pretty sure there's one "r" too many in UrnaryConstraint. -- _ | Peter J. Holzer | Story must make more sense than reality. |_|_) | | | | | h...@hjp.at | -- Charles Stross, "Creative writing __/ | http://www.hjp.at/ | challenge!"
signature.asc
Description: PGP signature
-- https://mail.python.org/mailman/listinfo/python-list