开发者

Inherit another object's methods

开发者 https://www.devze.com 2023-03-15 19:15 出处:网络
f = open(\'bobby_g.txt\', \'w\') f.write(\'Hey bobby!\') f.close() class BobFile: def __init__(self, x): self = open(x, \'r\')
f = open('bobby_g.txt', 'w')
f.write('Hey bobby!')
f.close()

class BobFile:
    def __init__(self, x):
        self = open(x, 'r')


a = BobFile('bobby_g.txt')
print a.read()
a.close()

I don't want to subclass the 'file' object, I want to create a BobFile object that then becomes another object(a file object) (and inherits all of its methods). So I can then use the BobFile object as if it were a file object..

Is th开发者_C百科is possible? I tried assigning the new file object to SELF of BobFile, but that didn't work...


attribute delegation?

class BobFile:
    def __init__(self, x):
        self.__file = open(x,'r')
    def __getattr__(self, name):
        return getattr(self.__file, name)

a = BobFile('/dev/random')
print a.read(20)
a.close()


What exactly are you trying to achieve? You can't create an object that becomes another object. Can you create a car that becomes an elephant? It's not reasonable. If you end up with something like this in your design, you should think of a new design.

So back up a little and think about what you're trying to do. If you just wish to do what your question says. Then simply create a class variable that you set to the file object in init. Then, create read() and close() methods in your BobbyFile class that call the respective methods of your file variable in the class.


It is bit confusing after reading your question title and your description. Is this what you are trying to achieve?

class myfile(file):
    def __init__(self, *args, **kwargs):
        file.__init__(self,*args,**kwargs)

o = myfile('foo','w')
o.write('something')
o.close()
0

精彩评论

暂无评论...
验证码 换一张
取 消