How does a method of a subclass become a method of the base class?
Peter J. Holzer
hjp-python at hjp.at
Sun Mar 26 14:48:25 EDT 2023
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.
|_|_) | |
| | | hjp at hjp.at | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230326/78ceac71/attachment.sig>
More information about the Python-list
mailing list