473,395 Members | 1,931 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

How to subclass file

I want to create a subclass of 'file' but need to open the file with os.open
(because I want to open it in exclusive mode), and need an additional method.

Because I need an additional method, I truly need a object of my sublass.
If I do something like

class myFile(file):

def __new__(cls, filename):
import os
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)

return os.fdoen(fd, 'w')

def myMethod(self):
do_something
then x = myFile('somefilename') is of type file, not myFile, and therefore
does not have myMethod as a valid method.

Now if I try:

class myFile(file):

def __new__(cls, filename):
import os
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)

obj = file.__new__(cls)

return obj

def myMethod(self):
do_something

Then it fails, because the 'file' constructor needs a filename. I can provide
the filename, but it will then try to re-open that file, and even if I did
manage to create an object file, how do I connect the file descriptor created
by os.open to my object ?
Thanks.
Yves.
http://www.SollerS.ca

Jun 27 '08 #1
1 3332
En Wed, 14 May 2008 21:23:26 -0300, Yves Dorfsman <yv**@zioup.com>
escribió:
I want to create a subclass of 'file' but need to open the file with
os.open
(because I want to open it in exclusive mode), and need an additional
method.

Because I need an additional method, I truly need a object of my sublass.
If I do something like

class myFile(file):

def __new__(cls, filename):
import os
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
return os.fdoen(fd, 'w')

def myMethod(self):
do_something
then x = myFile('somefilename') is of type file, not myFile, and
therefore
does not have myMethod as a valid method.
Use delegation instead of inheritance.

from __future__ import with_statement
import os

class myFile(object):
__slots__ = ['_file']

def __init__(self, filename):
fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL)
f = os.fdopen(fd, 'w')
object.__setattr__(self, '_file', f)

def __getattr__(self, name):
return getattr(self._file, name)

def __setattr__(self, name, value):
setattr(self._file, name, value)

def mymethod(self):
print "anything"
<output>
pyregular_file = open(r"c:\\temp\\regular.txt", "wt")
pyspecial_file = myFile(r"c:\\temp\\special.txt")
pyprint regular_file
<open file 'c:\\temp\\regular.txt', mode 'wt' at 0x00A411D0>
pyprint special_file
<__main__.myFile object at 0x00A3D1D0>
pyprint dir(regular_file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__',
'__getattribute
__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__',
'__reduce_ex__
', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding',
'fileno'
, 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read',
'readinto', 're
adline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write',
'writeli
nes', 'xreadlines']
pyprint dir(special_file)
['__class__', '__delattr__', '__doc__', '__getattr__', '__getattribute__',
'__ha
sh__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
'__re
pr__', '__setattr__', '__slots__', '__str__', '_file', 'mymethod']
pywith special_file:
.... special_file.write("hello\n")
.... special_file.mymethod()
....
anything
pyprint "closed?", special_file.closed
closed? True
</output>

(note that __enter__/__exit__ -used by the with statement- work fine, even
if not listed by dir(); also the "closed" attribute exists and is set
correctly)

Note also that myFile is *not* a subclass of file:

pyisinstance(special_file, file)
False

but it has all methods and attributes of file objects, even if
dir(special_files) doesn't list them. Duck typing in action - typical
Python code should work fine with this myFile object instead of a true
file object, but if you actually need a file subclass, I think you'll have
to write a C extension.

--
Gabriel Genellina

Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Frank Millman | last post by:
Hi all I have a question regarding inheritance. I have come up with a solution, but it is not very elegant - I am sure there is a more pythonic approach. Assume the following class definitions....
1
by: Gerry Sutton | last post by:
Hi All! I have noticed a strange behavior when using a constant identifier to initialize an instance list variable in a base class and then trying to modifying the list in subclasses by using...
5
by: Brett Kelly | last post by:
Sorry, for the somewhat confusing subject, but my problem is equally odd (imo). So, I have an assembly that contains an abstract class (File) and 5 other classes that all subclass it (Exe, Dll,...
5
by: spike grobstein | last post by:
So, I've got this project I'm working on where the app defines various classes that are subclassed by module packages that act like plugins... I'd like the packages to define a file path for...
18
by: Sandra-24 | last post by:
Can you create an instance of a subclass using an existing instance of the base class? Such things would be impossible in some languages or very difficult in others. I wonder if this can be done...
8
by: Lou Pecora | last post by:
I've been scanning Python in a Nutshell, but this seems to be either undoable or so subtle that I don't know how to do it. I want to subclass a base class that is returned from a Standard Library...
1
by: s.lipnevich | last post by:
Hi All, Is anything wrong with the following code? class Superclass(object): def __new__(cls): # Questioning the statement below return super(Superclass, cls).__new__(Subclass) class...
31
by: damacy | last post by:
hi, there. i have a problem writing a program which can obtain ip addresses of machines running in the same local network. say, there are 4 machines present in the network; , , and and if i...
6
by: Me | last post by:
I need to be able to acces non-virtual members of sublcasses via a base class pointer...and without the need for an explicit type cast. I thought a pure virtual getPtr() that acts as a type cast...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.