arguments problem~

B

black

Hi all~

i coded a class say named "A" which can receive arbitrary arguments and all works fine but problem came when i created another class "B" which inherited "A". it can not receive arguments as expected, ie it collected keywords arguments to nonekeywords arguments tuple and keep keywords dict empty. My destination is just to pass all keywords from A to B without any modification and same does nonekeywords. below is my code, I'd much appreciate if anyone could inspires me, thanx~

class A:
def __init__(self, *args, **kw):
print args
print kw
print
class B(A):
def __init__(self, *args, **kw):
A.__init__(self, args, kw)
a = A("a?", a_pro="a!")
b = B("b?", b_pro="b!")

you can see contents should be in kw of B was not in kw but args, how to fix it plz ?

Regards~
 
F

Francis Avila

black wrote in message ...

class B(A):
def __init__(self, *args, **kw):
A.__init__(self, args, kw)

Should be A.__init__(self, *args, **kw).

To illustrate:
.... return [args, kwargs]
....
f(1, 2, b=3) [(1, 2), {'b': 3}]
a = f(1, 2, b=3)
f(a) [([(1, 2), {'b': 3}],), {}]
f(*a) #Your error [((1, 2), {'b': 3}), {}]
f(*a[0], **a[1])
[(1, 2), {'b': 3}]

In a calling context, * and ** do the opposite of what they do in a function
definition context: they unpack tuple/lists and dicts into distinct
arguments and keyword arguments. By not calling A.__init__ with unpacked
arguments, you literally passed a tuple and a dict, and in the function
these got grouped together in args.

It's in the docs somewhere, I swear. :)
 
D

Dan Bishop

black said:
i coded a class say named "A" which can receive arbitrary arguments and all
works fine but problem came when i created another class "B" which
inherited "A". it can not receive arguments as expected, ie it collected
keywords arguments to nonekeywords arguments tuple and keep keywords dict
empty. My destination is just to pass all keywords from A to B without any
modification and same does nonekeywords. below is my code, I'd much
appreciate if anyone could inspires me, thanx~

class A:
def __init__(self, *args, **kw):
print args
print kw
print
class B(A):
def __init__(self, *args, **kw):
A.__init__(self, args, kw)

The above line should be

A.__init__(self, *args, **kw)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,937
Members
47,481
Latest member
ElviraDoug

Latest Threads

Top