SEARCH YOUR SOLUTION HERE  

Passing arguments to subclasses

May I ask a simple newbie question, which I presume is true, but for
which I can't readily find confirmation:

Let's say I have a parent class with an __init__ method explicitly
defined:

class ParentClass(object):
def __init__(self, keyword1, keyword2):
etc

and I subclass this:

class ChildClass(ParentClass):
# No __init__ method explicitly defined

Now I presume that I can instantiate a child object as:

child = ChildClass(arg1, arg2)

and arg1, arg2 will be passed through to the 'constructor' of the
antecedent ParentClass (there being no overrriding __init__ method
defined for ChildClass) and mapping to keyword1, keyword2 etc.

Have I understood this correctly
, John Dann wrote:
> May I ask a simple newbie question, which I presume is true, but for
> which I can't readily find confirmation:
>
> Let's say I have a parent class with an __init__ method explicitly
> defined:
>
> class ParentClass(object):
> def __init__(self, keyword1, keyword2):
> etc
>
> and I subclass this:
>
> class ChildClass(ParentClass):
> # No __init__ method explicitly defined
>
> Now I presume that I can instantiate a child object as:
>
> child = ChildClass(arg1, arg2)
>
> and arg1, arg2 will be passed through to the 'constructor' of the
> antecedent ParentClass (there being no overrriding __init__ method
> defined for ChildClass) and mapping to keyword1, keyword2 etc.
>
> Have I understood this correctly


Yes, but...

The nice things about Python is that you can use the interactive
interpreter to test such things in an instant. (And not have to wait
for a response from python-list. Like this:


>>> class ParentClass(object):
.... def __init__(self, keyword1, keyword2):
.... print 'ParentClass.__init__ called with', keyword1, keyword2
....
>>> class ChildClass(ParentClass):
.... pass
....
>>> child = ChildClass(123,456)
ParentClass.__init__ called with 123 456
>>>


Gary Herron


Posted On: Wednesday 7th of November 2012 08:13:11 PM Total Views:  330
View Complete with Replies




Related Messages:

passing a variable argument list to a function   (108 Views)
I'm trying to write a function that accepts a variable number of arguments and passes those arguments to another function. Here is an example: def foo(*args): print "I'm going to call bar with the arguments", args bar(args) This doesn't do quite what I want. For example, if I call foo(1,2,3,4) then it calls bar((1,2,3,4)). It passes a tuple rather than expanding the argument list back out. I suspect there's a simple bit of syntax that I'm missing -- can anyone give me a hand
passing control to other window   (140 Views)
i am trying to develop a application using Tkinter in which a new window pops out on a particular button press.though i can pass control automatically to that window using .force_focus() method and disabling all my widgets in previous window but the technique is not so clean. for eg. when u click 'save' a window pops out asking for location but u can still close your previous window using the 'cross-mark' on top right corner with save window still open. can anyone help me out!
2004 example, passing function error   (169 Views)
http://linuxgazette.net/109/pramode.html >>> >>>def sqr(x): return x*x .... >>>def cube(x): return x*x*x .... >>>sqr >>>a = [sqr, cube] >>>a[0](2) >>>def compose(f, g): return f(g(x)) .... >>>compose(sqr, cube, 2) 64 >>> but i get: >>> compose(sqr, cube, 2) Traceback (most recent call last): File "", line 1, in compose(sqr, cube, 2) TypeError: compose() takes exactly 2 arguments (3 given) this: >>> def compose(f, g, x): return f(g(x)) >>> compose(sqr, cube, 2) 64 works though .. so just a mistake on his part but it looks like he just copied his shell...has there been a change since 2004 inr egards to how you can pass functions as arguments to functions
pickle passing client/server design   (129 Views)
I am contemplating the need for a way to handle high speed data passing between two processes. One process would act as a queue that would 'buffer' data coming from another processes. Seems that the easiest way to handle the data would be to just pass pickles. Further, I'm thinking that using a unix domain socket would make this a simple way to pass high volumes of pickles. Are there any examples of an architecture like these, where a process is a client, sending pickles to a server listening on a domain socket I'm am thinking there would be a need to have a semaphore, and some ACK or NACK that the server process got the whole pickle.
Creating a python c-module: passing double arrays to c functions.segmentation fault. swig   (156 Views)
everybody, I'm building a python module to do some heavy computation in C (for dynamic time warp distance computation). The module is working perfectly most of the time, which makes it so difficult to track down the error. and I finally figured out that the strange segmentation faults I get from time to time have something to do with the length of the vectors I'm looking at. (So in this minimal example I'm doing completely useless distance measures on vectors with the same entry in all dimensions, but the errors seem to have nothing to with the actual values in the vectors, only with the lengths.) But somehow I haven't quite gotten the essential ideas of what one has to do to debug this module and I hope someone can give me some advice. The main problem is probably somewhere around passing the double vectors to the c module or reserving and freeing memory. so, for example list1,list2 = [0.1 for i in range(555)],[0.2 for i in range(1874)] ctimewarp(list1,list2) # see python file below works perfectly fine and if the vector has one more element list1,list2 = [0.1 for i in range(555)],[0.2 for i in range(1875)] ctimewarp(list1,list2) it dies with a simple Segmentation fault nothing more said :-S For very small lists again, no problem: list1,list2 = [0.1 for i in range(3)],[0.2 for i in range(4)] ctimewarp(list1,list2) for intermediate size I get an error and more information: list1,list2 = [0.1 for i in range(22)],[0.2 for i in range(99)] ctimewarp(list1,list2) give: *** glibc detected *** python: free(): invalid next size (fast): 0x0804d090 *** ======= Backtrace: ========= /lib/i686/libc.so.6[0xb7bed4e6] /lib/i686/libc.so.6(cfree+0x90)[0xb7bf1010] /home/kim/Documents/pythonprojects/alignator/ _timewarpsimple.so[0xb7aadc0c] /home/kim/Documents/pythonprojects/alignator/ _timewarpsimple.so[0xb7aae0db] /usr/lib/libpython2.5.so.1.0(PyCFunction_Call+0x107)[0xb7d5d8e7] ======= Memory map: ======== 08048000-08049000 r-xp 00000000 03:05 2344438 /usr/bin/python 08049000-0804a000 rwxp 00000000 03:05 2344438 /usr/bin/python 0804a000-080f3000 rwxp 0804a000 00:00 0 [heap] .....(truncated) When looping over these lengths of vectors, e.g. as I did in the python file below, it runs smooth for thousands of times before dying at 938 for the first list length and 1110 for the second. i noticed that the sum of the list lengths is 2048=2^11 and it often seems to die around that but that's just a guess... If anyone has a little advice or a code snippet on how to pass float lists to modules or anything of that kind, i would appreciate it very much! thanks a lot in advance cheers kim __________________________________ Below you can see the c file, the .i file for swig, and a little python script producing the errors: _______________ .c file: /* File : timewarpsimple.c */ #include #include #include double timewarp(double x[], int lenx, double y[], int leny) { // printf ("%d *******************************\n", lenx); // printf ("%d *******************************\n", leny); double prev; double recx[lenx+1]; double recy[leny+1]; double warp[lenx+2][leny+2]; int i,j; prev = 0.0; for (i = 0; i < lenx; i++) { recx[i]=x[i]-prev; prev = x[i]; } recx[lenx]=1.0-prev; prev = 0.0; for (i = 0; i < leny; i++) { recy[i]=y[i]-prev; prev = y[i]; } recy[leny]=1.0-prev; // recency vectors are done // let's warp warp[0][0]=0.0; for (i = 1; i < lenx+2; i++) { warp[i][0]=1.0; } for (j = 1; j < leny+2; j++) { warp[0][j]=1.0; } for (i = 1; i < lenx+2; i++) { for (j = 1; j < leny+2; j++) { warp[i][j]=fabs(recx[i-1]-recy[j-1]) + MIN(MIN(warp[i-1][j],warp[i] [j-1]),warp[i-1][j-1]); } } return warp[lenx+1][leny+1]; } ________________ .i file: %module timewarpsimple %include "carrays.i" %array_functions(double, doubleArray); %{ double timewarp(double x[], int lenx, double y[], int leny); %} double timewarp(double x[], int lenx, double y[], int leny); ________________ here's what I'm doing to compile: swig -python timewarpsimple.i gcc -c timewarpsimple.c timewarpsimple_wrap.c -I/usr/include/ python2.5/ ld -shared timewarpsimple.o timewarpsimple_wrap.o -o _timewarpsimple.so which goes thru without any problem. ________________ .py file: #!/usr/bin/python # -*- coding: UTF-8 -*- import timewarpsimple def ctimewarp(list1,list2): """ takes two lists of numbers between 0 and 1 and computes a timewarp distance """ print "timewarping" alen = len(list1) blen = len(list2) a = timewarpsimple.new_doubleArray(alen*4) # Create the first array # Why I have to reserve 4 times more space I don't know, but it's the only way to make it work... b = timewarpsimple.new_doubleArray(alen*4) # Create the second array for i,p in enumerate(list1): timewarpsimple.doubleArray_setitem(a,i,p) # Set a value. (a,i,0) gives identical errors for i,p in enumerate(list2): timewarpsimple.doubleArray_setitem(b,i,p) # Set a value warp = timewarpsimple.timewarp(a,alen,b,blen) print "result",warp timewarpsimple.delete_doubleArray(a) timewarpsimple.delete_doubleArray(b) #a,b = None,None return warp ########## the tests: #list1,list2 = [0.1 for i in range(22)],[0.2 for i in range(99)] #ctimewarp(list1,list2) for x in range(888,1111): for y in range(888,1111): list1,list2 = [0.1 for i in range(x)], [0.2 for i in range(y)] print len(list1),len(list2),len(list1)+len(list2) ctimewarp(list1,list2)
Re: Keyword passing to superclass written in C   (134 Views)
On Nov 27, 2007 6:47 AM, Sven Erik Knop wrote: > Hi > > I am getting slightly frustrated and wonder if you can help me. > > Consider a Python class Foo implemented in C++. I have declared an > initialization method like this > > static int > Foo_init(P4Adapter *self, PyObject *args, PyObject *kwds) > { > > } > > and I am subclassing Foo in Python, which works fine in principle, > except for passing keywords. > > Here is the subclass: > > class Bar(Foo): > def __init__(self, *args, **kwlist): > Foo.__init__(self, args, kwlist) > This passes the args tuple and the kw dict as 2 regular arguments. You need to expand them in the second call if you want them to be passed as args and kwargs - Foo.__init__(self, *args, **kwargs)
Re: passing command line arguments   (152 Views)
quoth the Brian McCann: > > > when I run the script show_args2.py > > # ./show_args2.py 1 2 3 > > I get the following error > > Traceback (most recent call last): > File "./show_args2.py", line 4, in > print 'The arguments of %s are "%s"' %s \ > NameError: name 's' is not defined > > > ##################################### > > this is the script > #!/usr/bin/python > import sys, string > print 'The arguments of %s are "%s"' %s \ > (sys.argv[0], string.join(sys.argv[1:])) You don't want the 's' on the last format operator. Try: print 'The arguments of %s are "%s"' % \ (sys.argv[0], string.join(sys.argv[1:])) > any help would be greatly appreciated > > -Brian -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972
Re: passing arguments with ampersands   (151 Views)
O.R.Senthil Kumaran wrote: >> Quote:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential >> Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt > >> when i put 'print sys.argv[1:]' at the very beginning of the script, all i >> get is this: >> >> Quote:['D:\\ftp\\Music\\Mixes'] >> > Can you share the portion of the code > Are you quoting the argument that you are passing > for e.g: > > #cat 1.py > import sys > print sys.argv[1] > > #python 1.py "I am able to print the spaces and & characters" > I am able to print the spaces and & characters > I suspect that the ampersand is being interpreted as a command terminator, and that the shell syntax error has been overlooked. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading -------------
Re: passing arguments with ampersands   (151 Views)
> Quote:\ftp\Music\Mixes & Compilations\Above & Beyond - Essential > Mix\001_Essential_Mix_2004-06-06_-_Above_and_Beyond.txt > when i put 'print sys.argv[1:]' at the very beginning of the script, all i > get is this: > > Quote:['D:\\ftp\\Music\\Mixes'] > Can you share the portion of the code Are you quoting the argument that you are passing for e.g: #cat 1.py import sys print sys.argv[1] #python 1.py "I am able to print the spaces and & characters" I am able to print the spaces and & characters -- O.R.Senthil Kumaran http://uthcode.sarovar.org
ctypes:passing python class instances through c and back   (222 Views)
Hi I have C code with requires me to register a python callback. I am able to get the callback working well using ctypes if I use global functions without any context argument for the callback. Now I want to register a python class member function for callback, and give "self" as the context argument at the time of callback registration. Then the c code can invoke the callback with self as the context argument class SomeClass(object): def __init__(self): self.msg = '' def callbackMethod(context): # self = somemagic(context)
Having lots of fun passing parameters ... help!   (123 Views)
I've defined a single method in Python using: def funcAdjacents(inputWord, outputFile): ... lots of boring stuff ... and then called it using: funcAdjacents("SampleWord","outputFile.file") Which works OK in Python - I get the results I want. But what I'm trying to do is get inputWord and outputFile to be parameters are passed on the command line, e.g. C:\Python\> myScript.py "SampleWord" "outputFile.file" And just to add to the fun, once I've reached this stage I would like to either a) be able to execute this .py file from a HTML environment or b) execute this file as a .exe and embed into HTML (which I can do). Has anyone got any ideas DAC.
passing arguments to tcpserver classes   (133 Views)
Is there an easy way to pass arguments to a handler class that is used by the standard TCPServer normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass, (arg1,arg2)) And have arg1, arg2 available via TCPHandlerClass.__init__ or some other way. Where TCPHandlerClass: class TCPHandlerClass(SocketServer.StreamRequestHandler): def handle(self): #handle stream events here#
Re: Newbie question about string(passing by ref)   (119 Views)
Steven D'Aprano wrote: ... > Python does NOT support pass by reference. Nor does it do pass by value. > Both of those models might describe what other languages do, but they > don't describe what Python does. > Python's passing model is different from both pass by reference and pass > by value, and there are circumstances where Python seems to be acting as > if it were doing one or the other. But it isn't. The model Python uses is > often (but not often enough...) called "pass by object" or "call by > sharing". > http://effbot.org/zone/call-by-object.htm > Steven. Wouldn't it make sense to say that Python passes arguments by binding objects to parameter names Thus, once you understand the concepts of "names" (vs. "variables") and "binding" (by contrast to "assignment") then you also understand the argument passing model in the same terms. Also, wouldn't it be fair to say that the class and def statements also bind names to objects (callable and class objects respectively). -- Jim Dennis, Starshine: Signed, Sealed, Delivered
Re: Newbie question about string(passing by ref)   (123 Views)
Duncan Booth wrote: > lazy wrote: >> I want to pass a string by reference. I understand that strings are >> immutable, but Im not >> going to change the string in the function, just to aviod the overhead >> of copying(when pass-by-value) because the >> strings are long and this function will be called over and over >> again. > You'll find it is pretty hard to get Python to copy a string even if you > wanted it to. About the only way is to break it apart and then construct a > new string with the same value from it. This, of course, is an implementation detail. There are other programming languages which use "interned" objects and, as far as I know, they are considered implementation details with undefined semantics. (In other words you are supposed to ignore this detail and not rely on the identity of any particular objects except those which are defined as such by the language). (An example, in Python, of an object with a defined identity would be "None" --- all references to "None" are intentionally references to a single object and it is the most notable case where the "is" operator is preferred). That said it seems to be trivially easy to "copy" a short string in the version of Python I'm using here: Python 2.4.4 (#2, Oct 20 2006, 00:23:25) [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> foo = "foo" >>> bar = "".join(list(foo)) >>> id(foo); id(bar); foo is bar -1211235616 -1211235296 False >>> -- Jim Dennis, Starshine: Signed, Sealed, Delivered
passing arguments from a python program to other while executing itwith exec() or spawn() in LINUX   (178 Views)
HI all, i have two python programs as 1.py and 2.py 1.py import os import sys processID=os.spawnl(os.P_WAIT,'/usr/local/bin/python','python','/ mywork/2.py ' + 'hi') 2.py import sys domain= str(sys.argv[1] ) print domain IN LINUX while executing 1.py,the argument 'hi' is not passed to the 2.py and error message is displayed as : python: can't open file '/mywork/2.py'.If i execute the program from shell like: python 2.py hi,then it works fine IN WINDOWS this is working fine PLEASE HELP.
UNIX credential passing   (134 Views)
I want to make use of UNIX credential passing on a local domain socket to verify the identity of a user connecting to a privileged service. However it looks like the socket module doesn't implement sendmsg/recvmsg wrappers, and I can't find another module that does this either. Is there something I have missed Kris
Keyword passing to superclass written in C   (106 Views)
Hi I am getting slightly frustrated and wonder if you can help me. Consider a Python class Foo implemented in C++. I have declared an initialization method like this static int Foo_init(P4Adapter *self, PyObject *args, PyObject *kwds) { } and I am subclassing Foo in Python, which works fine in principle, except for passing keywords. Here is the subclass: class Bar(Foo): def __init__(self, *args, **kwlist): Foo.__init__(self, args, kwlist) I have tested Foo and Bar as Python classes and passing the keywords is not a problem. If I create Foo in C++ and call it directly, I can pass the keywords no bother. But if I call Bar with keywords, it calls the C++ version of Foo with all arguments bunched together in "args" and not separated in args and keywords. What am doing wrong This is Python 2.5.1 - on Ubuntu 7.0.4 if that makes any difference.
JPype - passing to Java main   (110 Views)
I am trying to get JPype to pass a String into a Java class main function. Demonstration code below: =============JAVA============ package com; public class JPypeTest { public static void main(String args[]) { System.out.println(args[0]); } public void printArgument(String arg) { System.out.println(arg); } } ===========PYTHON=========== from jpype import * startJVM("C:/Program Files/Java/jdk1.5.0_12/jre/bin/server/jvm.dll","- Djava.class.path=C:/jpypetest/test/") com = JPackage("com"); jp = com.JPypeTest(); jp.printArgument('XXXX'); #WANT TO CALL main("arg") HERE!!!! shutdownJVM() =============================== What I want is to be able to call main() with an argument from the python file (using JPype) and have it echo args[0]. I can get this to work for printArgument(), but not for main().
Re: passing arguments with ampersands   (127 Views)
En Sat, 18 Aug 2007 09:24:35 -0300, SHY escribi: > theres no special portion of code, just the one that handles filenames > with > spaces. > the problem is that when i associate a file extension to my application > and > i open it, the filename is not quoted before passed as an arguement. i > dont > know if its the problem of windows or something, or it was just my fault > when i incorrectly associated the extension. How did you associate it Usually the registry entries are: HKCR\.ext = filetype HKCR\filetype = File Description HKCR\filetype\shell\open\command = "path\to\your\program" "%1" (Note the double quotes around %1) Get it right at the registry, and forget all that trickery joining sys.argv parts -- Gabriel Genellina
passing vars to py scipts in cron jobs   (129 Views)
What's the proper way to call a py script and pass in variables while doing cron jobs I can run the scripts fine from idle, python, etc using raw_input() to prompt users. The scripts have classes with methods that need arguments. Here's an example... I want to run c1.d1(v,v,v) then c2.d2(v,v,v) class c1: # User defined vars def d1(var1, var2, var3): pass class c2: # User defined vars def d2(var1, var2, var3): pass