[Tutor] Quacks like an object

Alan Gauld alan.gauld at btinternet.com
Tue Oct 25 02:06:33 CEST 2011


On 25/10/11 00:02, Christopher King wrote:
> Dear Tutors,
>      I am trying to make an object, which will appear exactly like an
> object of my choice. It will should be impossible to tell it is not the
> object.

We can get pretty close but I suspect its impossible to make it 100% 
reliable - otherwise Python itself would get confused!

 >  This is because I am making an object that modifies it methods
> so that if the methods make a change to the object, it will sync those
> changes to a file, but I don't want it to be another object,
> so foreign functions will not mistake for not being the object.

Sorry that bit lost me!
You want to persist data changes to a file? Thats easy enough.
But the last two lines sem disconnected fro the saving to file bit?

 > For example if, I used type on the object, it should return
 > the class of the object it is trying to mimic.

And presumably isinstance() too?

> but I had no luck. In a nutshell, I want an object that walks like
> another object, quacks like another object, and basically is another
> object.

But basically is NOT another object I think you mean.
If you really want it to be the other object then just make another 
instance cloning the attributes. But I don;t think thats really what you 
want?

> Is this possible?

If you are prepared to spend a lot of time implementing all the meta 
methods etc then you should be able to get pretty close. But it
will be tedious. I suspect there will almost certainly be a better 
solution if we understood the actual problem you are trying to solve. 
(The facade design pattern sounds likely for example!)


HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list