topskill.dev
CoursesTracks
0
All courses/Object Oriented Programming with PythonCombine small inherited capabilities
Inheritance and composition
10 / 13
← Object Oriented Programming with Python
○Define a class○Create two objects○Attach instance data○Read and update data○Class defaults○Shadow a class default○Write an instance method○Return a value○Initialize an object○Constructor defaults○Independent instance lists○Class body scope✦Module Quiz
○Bound methods○Function attributes○Classes are callable○A class method factory○Static methods○The property function○The property decorator○Computed properties○Read-only properties○Property setters✦Module Quiz
○Give objects a friendly string○Make repr useful for debugging○Add two value objects○Subtract value objects○Multiply a value by a scalar○Support reflected multiplication○Compare objects by value○Order value objects○Give an object a length○Choose an object truth value○Build a safe hashable key○Make an instance callable○Customize formatted output○Keep cleanup explicit✦Module Quiz
○Inherit an existing method○Recognize the object base○Extend initialization with super○Override one behavior○Extend a method through super○Substitute objects in a loop○Compose a service from a collaborator○Reserve attributes with slots○Keep slots in a subclass●Combine small inherited capabilities○Inspect method resolution order○Cooperate through a diamond✦Module Quiz
○Start an animal record○Record a rescued bird○Record a rescued fish○Give each animal a movement○Add a feeding service○Keep a rescue register○Group animals by habitat○Print the daily care report✦Module Quiz
○Open an account in cents○Deposit money○Withdraw available money○Add savings account data○Allow a current-account overdraft○Lock a fixed deposit○Calculate simple interest separately○Credit calculated interest○Register accounts by ID○Print a current statement✦Module Quiz
○Name a fixed set of statuses○Choose explicit enum values○Generate internal values with auto○Compare members, not raw codes○Reject duplicate enum values○Iterate over canonical members○Give enum members a method○Choose an enum truth rule○Check the enum type at a boundary○Describe a small dataclass record○Store an enum member in a dataclass○Use dataclass objects as enum values✦Module Quiz
○Intercept an attribute read○Handle class-level descriptor access○Intercept an attribute assignment○Keep descriptor storage per instance○Delete a managed value○Let the class supply a field name○Give a data descriptor priority○Allow a non-data descriptor override○Recognize property as a descriptor○Connect function binding to descriptors○Reuse one validation rule across fields○Initialize a descriptor-backed record✦Module Quiz
○Reject an invalid lobby size○Catch only the expected lookup error○Name a domain error○Carry useful exception details○Preserve the cause of a failure○Release a resource with finally○Declare an abstract contract○Implement a credit fee policy✦Module Quiz
○Validate a product record○Build a searchable catalog○Calculate a cart line○Add products to a cart○Remove a cart line○Summarize the cart○Freeze an order snapshot○Checkout without losing the cart○Register and track an order○Format invoice lines○Render the complete invoice○Route shop commands○Run a scripted shopping session○Launch the console shop✦Module Quiz

Combine small inherited capabilities

A quest card needs a label and a journal lookup path. The supplied mixins provide those separate capabilities without owning initialization. Combine them in QuestCard; the path is just a string, not a network request.

Python permits several bases in a class declaration: class Child(First, Second):. The child can inherit methods from both. The order of bases matters when more than one class supplies the same attribute, but this exercise avoids a conflict by giving each capability a distinct method name. The next lesson inspects how Python resolves the general case.

A small class intended to contribute reusable behavior is often called a mixin. That word describes a design role, not special Python syntax. These mixins expect the consuming object to have a code field. The concrete card owns that field and its initializer; the mixins simply read it. State expectations should be documented so combining classes does not become guesswork.

The example combines two independent text features. Neither has an initializer, so the final class does not need to coordinate competing setup routines. Your card similarly owns its setup in one place. Multiple inheritance involving initializers takes more care; the cooperative diamond lesson will introduce a compatible calling pattern rather than relying on accidental argument agreement.

Do not copy the methods into the card class. Inheriting them keeps each capability's definition in one location and demonstrates lookup across both bases. Composition could also solve many such problems, especially when collaborators have their own state or lifetimes. Use multiple inheritance here because the exercise deliberately models small capabilities of the same object.

The tests check both behaviors with different codes and verify the declared base order. A class that happens to return matching strings without inheriting the capabilities would miss the requested relationship. The observable result should come from the same card instance through two inherited method names.

A small example

python
class LoudText:
    def loud(self):
        return "HELLO"

class QuietText:
    def quiet(self):
        return "hello"

class Voice(LoudText, QuietText):
    pass

voice = Voice()
print(voice.loud(), voice.quiet())

Your Task

  1. Change the supplied QuestCard declaration to inherit from LabelMixin then JournalMixin, in that order. Keep its initializer and inherit print_label() and journal_path() without redefining them.

Edit main.py and use Run to inspect the supplied check. Leave that check unchanged; Submit tests your method with other values too.

Hint 1
1 / 1
HINT 1

The concrete class owns the data; its two bases supply the capabilities.

Files
  • ⋄main.py
Loading editor…
Press Run to execute your code.