speedmancs
speedmancs

Reputation: 369

Why __init__ in python fail

I'm using python2.7 to define a function like this

def foo(*args, **kwargs):
    print 'args = ', args
    print 'kwargs = ', kwargs
    print '---------------------------------------'

and by calling foo(3), the output is as the following:

args =  (3,)
kwargs =  {}

which is desired.

But as for __init__ function in a class in which the parameters are the same form as foo, I can't instantize the class Person by invoking Person(3)

def Person():
    def __init__(self, *args, **kwargs):
        print args
        print kwargs
x = Person(3)

The output is

    x = Person(3)
TypeError: Person() takes no arguments (1 given)

That confused me a lot, have I missed something?

Upvotes: 0

Views: 122

Answers (1)

TerryA
TerryA

Reputation: 59974

You probably meant to create a class instead of a function:

class Person():
    def __init__(self, *args, **kwargs):
        print args
        print kwargs

__init__ is for classes :).

Upvotes: 6

Related Questions