Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using functools.partial within class structure, "name 'self' is not defined"

Below is a significantly simplified version on my code. After the __init__() there are several functions.

I am trying to use functools.partial to create different versions of a basic comparison function, which references a function created earlier in the class, calculation. One version of this comparison function might be the grade_comparison seen below.

class Analysis(mybaseclass):

    def __init__(self, year, cycle):
....

    def calculation(self, subject):
        print subject

    def comparison(subject, **kwargs):
        self.calculation(subject)

    grade_comparison = functools.partial(comparison, infoList1 = ['A', 'B'])

When I run my code, there is an error, NameError: global name 'self' is not defined. I have tried adding self in many combinations that seemed logical - one example below.

self.grade_comparison = functools.partial(comparison, self, infoList1 = ['A', 'B'])

This change resulted in this error, NameError: name 'self' is not defined When I add self to the comparison function (see below):

def comparison(self, subject, **kwargs):
        self.calculation(subject)

I get this error, TypeError: comparison() takes at least 2 arguments (1 given). Please let me know if you need more context! As mentioned, this is the barebones of the code.

like image 779
Emily K Avatar asked Oct 19 '22 18:10

Emily K


1 Answers

I think you can achieve what you want without partial:

class Analysis(object):

    def calculation(self, subject):
        print subject

    def comparison(self, subject, **kwargs):
        self.calculation(subject)

    def grade_comparison(self, subject):
        return self.comparison(subject, infoList1=['A', 'B'])
like image 58
Mike Müller Avatar answered Oct 21 '22 16:10

Mike Müller