0

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?

1

1 Answer 1

6

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 :).

Sign up to request clarification or add additional context in comments.

4 Comments

So, how can I use *args and **kwargs for the construct function of a class. I'm initially trying to overload the initialization function within a class but python doesn't support that feature. The desired calling is as the following: a = Person(name="xxx") b = Person(age=16)
@speedmancs: You do it exactly the way you had it in your code, except without accidentally using def where you meant class.
Thank you, I've really made this mistake:)
@speedmancs Don't worry, everyone makes mistakes every once in a while ;). Also, don't forget to accept the answer :)!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.