Home > Enterprise >  Imported function that takes one argument displays error that 2 arguments were given
Imported function that takes one argument displays error that 2 arguments were given

Time:09-24

I have a class file called importDemo.py that is at the same directory as my main file called FunctionsDemo.py

Here is the content of importDemo.py:

class basicFunction:

    myName = "John"

    def __init__(self) -> None:
        print("Constructor has been called")

    def greet(name):
        print(f"Hi there {name}\n\n")

And this is the main FunctionsDemo.py file:

from importDemo import basicFunction as func

firstObj = func()
firstObj.greet(firstObj.myName)

func.greet("Ben")
print(firstObj.myName)

When I try to run FunctionsDemo.py, it displays this error

TypeError: greet() takes 1 positional argument but 2 were given

Is there anything I'm doing wrong here? I only given greet() one argument? I was hoping I can trigger both constructor and greet() with no errors.

EDIT: I got confused and mistakenly used instance and class functions

if I used func(), it goes without saying that I need to include the self in my function. Thanks for clarifying.

CodePudding user response:

You are using greet as a method, right? Then you should define it like that:

def greet(self,name):
        print(f"Hi there {name}\n\n")

CodePudding user response:

In python class a method parameters start with one default parameter called self which reference the class object. You can use the self to access public variables declared within the class so in your code you should include the self in your greet method list of parameters like so:

   def greet(self, name):
          print(f"Hi there {name}\n\n")
  • Related