[Tutor] Initializing with a call like: someClass.open("someFile")?

Ryan Davis ryan at acceleration.net
Mon Feb 21 16:34:31 CET 2005


You could make the __init__ take the filename:

def __init__(self, filename=None):
   #do whatever

And then instantiate the object like:
>>>x = someClass(filename="someFile")

Alternatively, you could make the Open function a module level function, defined in someClass.py, but not in the actual class
definition.

There's also a way to do it with @staticmethod, but I haven't ever touched that.

Thanks,
Ryan 

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Christian Meesters
Sent: Monday, February 21, 2005 5:01 AM
To: tutor at python.org
Subject: [Tutor] Initializing with a call like: someClass.open("someFile")?


Hi

My cryptic subject is perhaps not sufficient - I'll try to make it a little better:
Assume you'd like to write something like: 

import someClass
x = someClass.open("someFile")

Here '.open' should read in the data and initialize the instance - with or without calling __init__. 
How is this to implement? Up to now I rather wrote something like x = 
someClass(somePrepFunction("someFile")) where the return value of somePrepFunction was used 
to initialize x or called the conventional 'open' within __init__. But is there no direct approach like 
in my pseudo-code?
My problem is that if I simply define open as a method of someClass (with 
def open(self,file_name): 
	#somecode
	pass
) all I get is:
TypeError: unbound method open() must be called with someClass instance as first argument 
(got str instance instead)
Which is perfectly understandable. But what is a possible workaround? (Instead of 'open' I could, 
of course, better use some other keyword which is no Python keyword.)

Any hints?

Thanks a lot in advance.
Christian
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list