-3

[edit] Thanks everybody for the help. This did produce an answer and I have marked the correct answer.

[edit] I apologize for this hastily formulated question. I am trying to express what my problem is and the code snippet was written as an abstraction of what I am trying to do. I have added a new subobject of A and I need to be able to call the anotherFunc on the attribute aThing, as well as A's native functions.

I have a class, A, with function func(). I have an instance of A that is being reinitialized constantly.

class B(object):

    def __init__() :
       self.aThing = A()

    def foo(aFunction, args):

      self.aThing = A()
      self.aThing.aFunction(args)

    def bar() :
       self.foo(A.func, anArg)

    def bam()
       self.foo(A.aThing.anotherFunc)

class A(object) :

     def __init__() :
         self.aThing = C()

     def func() :
         doSomething

class C(object):

     def anotherFunc()
        doAnotherThing


x = B()
x.bar()
x.bam()

How do I pass the function func so that it is called on the newly initialized object self.aThing?

user442920
  • 857
  • 4
  • 21
  • 49

2 Answers2

2

If I understand you correctly, you are probably looking for this:

class B(object):

    def foo(self, aFunction, args):
        self.aThing = A("foo")
        aFunction(self.aThing, args)

    def bar(self) :
        self.foo(A.func, ["some", "stuff"])

class A(object):

    def __init__(self, name):
        self.name = name

    def func(self, args) :
        print "func called on", self.name, args

x = B()
x.bar()

Note all those self parameters, those are important! Output:

func called on foo ['some', 'stuff']

The interesting line is this: aFunction(self.aThing, args). To understand why this works, remember that aThing.func(args) is actually the same as A.func(aThing, args).

Community
  • 1
  • 1
tobias_k
  • 81,265
  • 12
  • 120
  • 179
1

It's not totally clear, but you may want:

class B(object):

    def __init__(self): # note 'self' argument
        self.aThing = A()

    def foo(self, aFunction, args): # and here
        self.aThing = A()
        getattr(self.aThing, aFunction)(args)

    def bar(self): # and here
        self.foo("func", anArg) # note string of function name

This will call func on the new A instance, which it accesses using the name of the function and getattr. However, note the following caveats:

  • As defined, A.func doesn't actually have any parameters (again, including self);
  • It is not clear whether the args parameter of B.foo should be a single argument or a tuple of positional arguments (as it is usually used - *args); and
  • Where does anArg come from?
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437