dtkx
dtkx

Reputation: 105

Passing class objects to another class method Python

I am trying to understand where my mistake lies and I was hoping you could please help me.

I have this code:

import copy
class FooInd():
    def __init__(self):
        self.a=1

class Planning():
    def foo(self,pop):
        print(pop.a)

    def main():
        ind=FooInd()
        Planning.foo(copy.deepcopy(ind))
if __name__ == "__main__":
    Planning.main()

However I keep receiving this error:

Planning.foo(copy.deepcopy(ind))
TypeError: foo() missing 1 required positional argument: 'pop'

I believe that the mistake is not in the foo method definition, but in my class initiation of the FooInd, however I have checked the Python documentation for classes and I could not find a solution.

Does anyone have a clue of what could I try or where can I check? Many thanks in advance!

Upvotes: 0

Views: 147

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155373

You call Planning.foo on the class, not an instance of the class. You provided the second argument it requires, but not the self argument.

You have two choices:

  1. Construct a Planning instance to call foo on:

    def main():
        ind=FooInd()
        Planning().foo(copy.deepcopy(ind))
        #       ^^ Makes simple instance to call on
    
  2. Make foo a classmethod or staticmethod that doesn't require an instance for self:

    class Planning():
        @staticmethod  # Doesn't need self at all
        def foo(pop):
            print(pop.a)
    

Upvotes: 1

quamrana
quamrana

Reputation: 39354

I think you meant to instantiate Planning before calling methods on it:

import copy
class FooInd():
    def __init__(self):
        self.a = 1

class Planning():
    def foo(self, pop):
        print(pop.a)

    def main(self):
        ind = FooInd()
        self.foo(copy.deepcopy(ind))
if __name__ == "__main__":
    p = Planning()
    p.main()

Output:

1

Upvotes: 1

Related Questions