简体   繁体   中英

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

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']

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.

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