Search code examples
pythonclassmethodsattributes

How to reference object methods in a class variable in Python


I have this class which works :

class A:
    def __init__(self):
        self.checks = (self.check1, self.check2)

    def check1(self):
        print("check1")

    def check2(self):
        print("check2")

    def run_all_checks(self):
        for check in self.checks:
            check()

a = A()

a.run_all_checks()

Now I think attribute checks should not belong to every A object, but should be a class attribute, so I'd like to write :

class A:
    checks = (self.check1, self.check2)

    def check1(self):
        print("check1")

    def check2(self):
        print("check2")

    def run_all_checks(self):
        for check in self.checks:
            check()

a = A()

a.run_all_checks()

This version does not work, giving error :

NameError: name 'self' is not defined

Is there a way to achieve that ?


Solution

  • A property probably gets you closest to what you're trying to achieve.

    This way, self.checks gives the tuple of the two check functions, but it does so through a getter function that's called on the fly: so there's no extra storage requirement (albeit that storing two references to functions doesn't take much space).

    class A:
        @property
        def checks(self):
            return (self.check1, self.check2)
    
        def check1(self):
            print("check1")
    
        def check2(self):
            print("check2")
    
        def run_all_checks(self):
            for check in self.checks:
                check()
    
    a = A()
    
    a.run_all_checks()
    

    which as expected prints

    check1
    check2