ajknox
ajknox

Reputation: 13

Python Function Reference Object Attributes

How do I pass a function to an object that accesses attributes in the object's scope?

This works:

class Foo():
    def __init__(self, some_func):
        self.some_func = some_func
        self.stats = 'some stats'
    def execute(self):
        return self.some_func()
def bar():
    return x.stats      
x = Foo(bar)
x.execute()

but I dislike that I have to write a new bar if I rename the object.

What I actually want to write is more like:

class Foo():
    def __init__(self, some_func):
        self.some_func = some_func
        self.stats = 'some stats'
    def execute(self):
        return self.some_func()
def bar():
    return self.stats      
x = Foo(bar)
x.execute()

and have the self in bar() pick up stats from any Foo object it get's passed to, regardless of how it's named. I can't figure out a smart way to do this.

Are there good ways to reference attributes of Foo objects without changing Foo? Alternately, could you enable this by making Foo's call to some_func() smarter? Does this vary between python 2 and 3?

Upvotes: 1

Views: 349

Answers (1)

quamrana
quamrana

Reputation: 39354

Why can't the object be passed in at runtime?

class Foo():
    def __init__(self, some_func):
        self.some_func = some_func
        self.stats = 'some stats'
    def execute(self):
        return self.some_func(self)

def bar(self_):
    return self_.stats      

x = Foo(bar)
x.execute()

The above function bar() works because in python nothing is really private as long as you know the name of an attribute.

Upvotes: 4

Related Questions