3

I'm learning python. I have created a class visualizer which contains 2 methods. Now I want to call the first method inside my second method. I read I have to use self:

def method2(self):
    self.method1()

This works. Now I'm adding additional parameters:

def method2(self, param1, param2, param3):
    self.method1()

And I call it from my main.py:

xx.method2(param1, param2, param3)

Now I get an error:

missing 1 required positional argument: 'param3'

I checked, param3 is there and the sequence of parameters is the same. I think it's conflicting with self.

How can I solve this? Do I need an init method inside my class?

EDIT: In my Main:

from project.visualizer import Visualizer
vsl = Visualizer

vsl.method2(param1, param2, param3)
DenCowboy
  • 13,884
  • 38
  • 114
  • 210
  • 1
    Make sure you are calling the method of an instance not of the class. There are also class methods in Python. – Klaus D. Apr 29 '18 at 16:33
  • 1
    What is `xx`? Is it an instance of your class? You need to provide a *compete* example: the class, how you create an instance of the class, and how you invoke the method(s). – chepner Apr 29 '18 at 16:33
  • 1
    No you don't need an `__init__`, but you _do_ need to create an instance of the class so you can call the method correctly. – PM 2Ring Apr 29 '18 at 16:36

2 Answers2

7
vsl = Visualizer

This doesn't create an instance of Visualizer like you intend. As written it causes vsl to point to the Visualizer class rather than an instance of the class. When you call vs1.method2() it's as if you've written:

Visualizer.method2(param1, param2, param3)

It should be:

vsl = Visualizer()

If Visualizer's constructor takes parameters, pass those in.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

To call method, you have initialize the class first.

x = Visualizer()
x.method2(...)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
BugHunter
  • 1,194
  • 2
  • 9
  • 15