Home > Mobile >  Improving python classes' methods
Improving python classes' methods

Time:10-21

I have come across an issue during set-up python classes. I have such classes:

class ModifierType(ABC):
    """Represents a generic modifier type."""
    ...


class DefaultModifierType(ModifierType):
    """Represents a default modifier type."""

    @staticmethod
    def check_modifier(modifier_id: str, item_name: str, default_modifiers: tuple[str]) -> None:
        ...


@dataclass
class RequiredModifierType(ModifierType):
    """Represents a required modifier type."""

    default_quantity: int = None
    action_codes: list[str] = field(default_factory=list)

    def check_modifier(self, modifier_id: str, item_name: str) -> None:
        ...


@dataclass
class Modifier:
    """Represents a generic modifier of group."""

    modifier_id: str
    modifier_type: ModifierType

And now I also have the outer function that runs kind of such code:

if isinstance(modifier.modifier_type, RequiredModifierType):
    modifier.modifier_type.check_modifier(
        modifier_id=modifier.modifier_id,
        item_name=item_name
    )
elif isinstance(modifier.modifier_type, DefaultModifierType):
    modifier.modifier_type.check_modifier(
        modifier_id=modifier.modifier_id,
        item_name=item_name,
        default_modifiers=default_modifiers
    )

The issue: as I figured out I cannot create an abstract method for ModifierType class because it has different params in DefaultModifierType and RequiredModifierType respectively. So I'd like to know if there's any opportunity to create this abstract method? If not, the checks better to move into Modifier class and check the instance of modifier_type there?

CodePudding user response:

You could add some further arguments, give them a default value, and ignore them where they are irrelevant or don't make sense.

class ModifierType():

    @staticmethod
    def check_modifier(modifier_id: str, item_name: str, default_modifiers: tuple[str] = None) -> None:
        ...

class DefaultModifierType(ModifierType):
    """Represents a default modifier type."""

    @staticmethod
    def check_modifier(modifier_id: str, item_name: str, default_modifiers: tuple[str]) -> None:
        assert (default_modifiers is not None)
        ...

However, if they really do have quite different signatures, it is worth considering that the two methods are not conceptually the same, and should be different methods that the calling side needs to explicitly distinguish.

  • Related