简体   繁体   中英

Abstract Method using Implementation level method

I'm implementing some classes for adjusting prices in my Ecommerce site: each class represents a different pricing adjustment strategy and belongs to an AbstractBaseClass which stipulates two methods: transform_price and transform_array .

class PricingModel(abc.ABC):
    @abc.abstractmethod
    def transform_price(self, price):
        ...

    def transform_price_array(self, price_array):
        return [self.transform_price(price) for price in price_array]

Since transform_array is simply a list comprehension of the transform_price method (which is, of course, implementation specific) I was hoping there would be some way to fully abstract this method in a way such that it still executes the implementation-specific method transform_price .

For example I would like to be able to define a PricingModel:

class PriceRatio(PricingModel):
    def __init__(self, **kwargs):
        ...
    
    def transform_price(self, price):
        ...
        return new_price
        
    # Note the abscence of a transform_price_array method!

While still being able to access the transform_price_array method defined in the abstract class:

_ = PriceRatio.transform_price_array([1,2,3,..])

Turns out this behaviour is enabled by default.

Removed all of my implementations of the transform_price_array method, leaving only the abstract method and all my tests still passed!

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM