sinG20
sinG20

Reputation: 151

Optional arguments in class methods

I have a class function where if optional parameter(yaml file) is passed then read the values and pass it as optional parameters to the def books() function. But executing the below code, I get error as 'name 'self' is not defined. How can I read the yaml items into the books function as an optional parameter?

class Price:
    def __init__(self, *args):
        if args:
            with open(args, 'r') as f:
                stream = yaml.load(f, Loader=yaml.FullLoader)
            bookname= stream['book']['name']
            self.param = bookname
        else:
            self.param = None
        return self.param 

    def books(self, file, name=self.param):
         print(file,name)

Upvotes: 0

Views: 404

Answers (1)

tania
tania

Reputation: 2315

This error seems to occur because of the .books() method, not the optional arguments. You cannot refer to self.param in the method signature. Instead, you need to access this attribute within the method. For example, based on your requirements, you could rewrite it as such:

def books(self, file, name=None):
    name_to_print = name or self.param # take the name if provided or the self.param
    print(file, name_to_print)

Finally, another issue you'll come across is that the class constructor (__init__()) shouldn't be returning self.param, but None (i.e. it shouldn't be returning anything). The moment you set self.param above, it becomes an attribute of the class instance and you don't need to return it. So, I would remove the row return self.param.

Upvotes: 3

Related Questions