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

Kent Johnson kent37 at tds.net
Mon Feb 21 12:29:26 CET 2005

Christian Meesters wrote:
> 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?

You can make your code work as written by making open() a module-level function in someClass.py. 
Call the function fromFile() to avoid redefining open. Assuming the class has a constructor that 
takes a string argument:

## someClass.py
def fromFile(f):
   data = open(f).read()
   return someClass(data)

class someClass:
   def __init__(self, data ):
     # init from data

Another way to do it, if this is the only way you create someClass instances, is to put the file 
read right in __init__():
class someClass:
   def __init__(self, f):
     data = open(f).read()
     # init from data

Finally, you can implement fromFile() as a classmethod of someClass:

class someClass:
   def __init__(self, data ):
     # init from data

   @classmethod@  # requires Python 2.4
   def fromFile(cls, f):
     data = open(f).read()
     return cls(data)

Clients would do this:
from someClass import someClass
x = someClass.fromFile("someFile")

See this thread on comp.lang.python for more discussion of a similar requirement:


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

Several possibilities:
- you can make a function to do what you want:

> 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