Python generic method scope -
i've got class wraps functions metadata, in particular parental relationship other instances:
class foo(object): def __init__(self, func, parent): self.func = func self.parent = parent self.parent_func = self.parent.func
in few cases, use foo
wrap function internally calls foo's function:
def f(x): return str(x).title() def g(x): return self.parent_func(x) = foo(f) b = foo(g, a) print b.func("april cruellest month") >>> april cruellest month
problem g
isn't method until b
runs foo.__init__
, doesn't have self.
i'm assuming there's rather fundamental i'm missing scoping, object methods, or functions' first-class citizenship status, , appreciate point in right direction.
edit: looks above genericized example threw folks off, i'm adding more specific example below. idea of class each instance integer property (primality, perfection, list of factors, etc), , contains function tests integer property (returning bool or answer, case base be).
def f(n): # returns list of factors of n def s(n): return len(self.parent_func(n))==2 # checks if n semiprime factors = foo(f) semiprime = foo(s, factors)
it seems question boils down "how can dynamically add method object", the short answer don't (1). objects can have attributes can functions, , that's fine, these functions not become methods , don't behave methods. example if foo.attr sum
foo.attr(x)
same sum(x)
not sum(foo, x)
.
your question has functional "aroma" it, if wanted drop class/object stuff , go functional route this:
def identity(x): return x def f(n): return [i in range(1, 10) if (n % == 0)] def s(factors): return (len(factors) == 2) def foo(func, helper=identity): def innerfunc(n): return func(helper(n)) return innerfunc = foo(f) print a(6) # [1, 2, 3, 6] b = foo(s, a) print b(5) # true
if doesn't appeal you, suggest thinking of func
, parent
attributes on foo
class data attached objects, not methods, , work out problem there. logic associated class should live inside proper methods. these methods can refer data needed. here's simple example:
class foo(object): def __init__(self, func, parent=none): self.func = func self.parent = parent def run(self, n): if self.parent none: return self.func(n) else: return self.func(self.parent.run(n)) = foo(f) print a.run(6) # [1, 2, 3, 6] b = foo(s, a) print b.run(5) # true
(1) methods belong class not object, question should how can attach object behaves method.
Comments
Post a Comment