teddybear123
teddybear123

Reputation: 2424

Creation of Classes?

I am new in python and trying to figure out how to modularize my functions. My project is a unit testing framework for Restful APIs. For brevity I've simplified the code.

type_parser.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--type', help='a or b')
args = parser.parse_args()

def A(func):
    def return_func():
        if args.type == "b":
          return func()
        else:
          pass
    return return_func

def B(func):
    def return_func():
        if args.type == "a":
          return func()
        else:
          pass
    return return_func

api_funcs.py

from type_parser import *

class ApiFunctions:

    @A
    def login():
        print "cool"
    @B
    def logout()
        print "not cool"

main.py

from api_funcs import *

api = ApiFunctions()

def __main__():
    api.login()
    api.logout()

__main__()

CLI

python main.py --type=a

Outcome

Expected:

cool

Actual:

TypeError: return_func() takes no arguments

It works if I take api functions out of a class and call it straight up, but I would want to make it more abstract since there will be 3 sets of APIs

Update - I figured out the answer

class ApiFunctions:

    @A
    def login(self):
        print "cool"
    @B
    def logout(self)
        print "not cool"


def A(func):
        def return_func(self):
            if args.type == "b":
              return func(self)
            else:
              pass
        return return_func

Upvotes: 2

Views: 89

Answers (1)

pltrdy
pltrdy

Reputation: 2109

In python the object itself has to be explicitely part of method singature. Thus you need to write: def login(self):

Writing self.login is kinda like ()* writing login(self). Since login() takes no argument you get an error.


(*) said kinda like, don't write it


api_funcs.py

from type_parser import *

class ApiFunctions:

    @A
    def login(self):
        print "cool"
    @B
    def logout(self)
        print "not cool"

Upvotes: 1

Related Questions