Senthilkumar Annadurai
Senthilkumar Annadurai

Reputation: 418

Python+Flask: __init__() takes 2 positional arguments but 3 were given

I am from Java world and new to python and so to Flask. Here is my views.py

from app import app

class Employee:
    def __init__(id,name): self.id = id; self.name = name;

@app.route('/')
@app.route('/index')
def index():
    return Employee(12345,"MyName")

In the function index(), when i tried to return "Hello World" without class Employee in the file and run the server, Hello World string was written to the webpage.

I then thought of outputting a json,

{"id":"12345","name":"MyName"}

So I started to introduce a class Employee and created a constructor to pass id and name.

Unfortunately it started showing this error.

File "C:\python\microblog\app\views.py", line 9, in index return Employee(12345,"MyName")

By the way, here i assume that if I can get rid of the error, flask would be able to convert the object to json by taking it as default mimetype for objects.

I had look at these answers, but didn't help with my knowledge.

Upvotes: 2

Views: 6041

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

Python "methods" are really functions and no pointer to the current instance is magically inserted in the function's scope, so you have to declare your first argument as a reference to the current instance (by convention this argument is named self) - or as a reference to the current class if it's a classmethod (and then the first argument is - by convention - named cls).

When the function name is looked up on an instance, it's turned into a (callable) method object that keeps a reference to both the function and the current instance and inserts the instance as the first argument to the function call, as explained here : https://wiki.python.org/moin/FromFunctionToMethod - so you dont have (and must not) explicitely pass the current instance when calling the method.

NB : I understand this might seems weird (and worse) coming from the Java world, but there are actually quite a few good reasons for this peculiar design, as you'll probably find out by yourself when you'll start exploring the dynamic programming / metaprogramming part of Python.

Upvotes: 4

oxana
oxana

Reputation: 395

In first argument on __init__ you must pass self:

class Employee:
    def __init__(self, id,name): 
       self.id = id; self.name = name;

Because self it's ref ob object Employee. Every Python object has two special method: __new__ and __init__. The first method for create object, it hasn't ref on object (self) and the second for initialise created object so it has ref named self.

Upvotes: 3

Related Questions