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

Cameron Simpson cs at cskk.id.au
Sun Mar 26 18:44:00 EDT 2023


On 26Mar2023 22:36, Jen Kris <jenkris at tutanota.com> wrote:
>At the final line it calls "satisfy" in the Constraint class, and that 
>line calls choose_method in the BinaryConstraint class.  Just as Peter 
>Holzer said, it requires a call to "satisfy." 
>
>My only remaining question is, did it select the choose_method in the 
>BinaryConstraint class instead of the choose_method in the 
>UrnaryConstraint class because of "super(BinaryConstraint, 
>self).__init__(strength)" in step 2 above? 

Basicly, no.

You've omitting the "class" lines of the class definitions, and they 
define the class inheritance, _not "__init__". The "__init__" method 
just initialises the state of the new objects (which has already been 
created). The:

     super(BinaryConstraint,_ self).__init__(strength)

line simply calls the appropriate superclass "__init__" with the 
"strength" parameter to do that aspect of the initialisation.

You haven't cited the line which calls the "choose_method" method, but 
I'm imagining it calls "choose_method" like this:

     self.choose_method(...)

That searchs for the "choose_method" method based on the method 
resolution order of the object "self". So if "self" was an instance of 
"EqualityConstraint", and I'm guessing abut its class definition, 
assuming this:

     class EqualityConstraint(BinaryConstraint):

Then a call to "self.choose_method" would look for a "choose_method" 
method first in the EqualityConstraint class and then via the 
BinaryConstraint class. I'm also assuming UrnaryConstraint is not in 
that class ancestry i.e. not an ancestor of BinaryConstraint, for 
example.

The first method found is used.

In practice, when you define a class like:

     class EqualityConstraint(BinaryConstraint):

the complete class ancestry (the addition classes from which 
BinaryConstraint inherits) gets flatterned into a "method resultion 
order" list of classes to inspect in order, and that is stored as the 
".__mro__" field on the new class (EqualityConstraint). You can look at 
it directly as "EqualityConstraint.__mro__".

So looking up:

     self.choose_method()

looks for a "choose_method" method on the classes in 
"type(self).__mro__".

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list