Javier Lopez Tomas
Javier Lopez Tomas

Reputation: 2342

How to extend a list from a method of inherited class

I have two classes: BaseClass and Antifraud, which is derived from BaseClass. There is a method in BaseClass that have a list, like this:

class BaseClass:
    def __init__(self):
        pass

    def create_metrics(self):
        self.metrics_list = ['score',
                             'precision',
                             'recall']

I want that when I instantiate the class Antifraud, the list self.metrics_list will be the same as before plus 'f1'. I have tried the following:

class Antifraud(BaseClass):

    def __init__(self):
        super().__init__()

        self.metrics_list.extend(['f1'])

a = Antifraud()

But I get the error:

AttributeError: 'Antifraud' object has no attribute 'metrics_list'

How could I solve my issue? Is it even possible to achieve? Thanks

Upvotes: 1

Views: 37

Answers (2)

kederrac
kederrac

Reputation: 17322

you can call the create_metrics method before to extend self.metrics_list, by calling first create_metrics you are creating self.metrics_list:

class Antifraud(BaseClass):

    def __init__(self):
        super().__init__()
        self.create_metrics()
        self.metrics_list.extend(['f1'])
print(Antifraud().metrics_list)

output:

['score', 'precision', 'recall', 'f1']

Upvotes: 1

loutre
loutre

Reputation: 894

It can be considered a bad practice to not initialize instance's attributes outside of __init__

You can update your BaseClass to

    class BaseClass:
        def __init__(self):
            self.metrics_list = ['score', 'precision', 'recall']

and then your AntiFraud class will work.

Upvotes: 0

Related Questions