views:

79

answers:

2

So if I have a class like:

CustomVal

I want to be able to represent a literal value, so like setting it in the constructor:

val = CustomVal ( 5 )

val.SomeDefaultIntMethod

Basically I want the CustomVal to represent whatever is specified in the constructor.

I am not talking about custom methods that know how to deal with CustomVal, but rather making it another value that I need.

Is this possible?

Btw 5 is just an example, in reality it's a custom COM type that I want to instance easily.

So by referencing CustomVal, I will have access to int related functionality (for 5), or the functionality of the object that I want to represent (for COM).

So if the COM object is RasterizedImage, then I will have access to its methods directly:

CustomVal.Raster () ...

EDIT: This is what I mean: I don't want to access as an attribute, but the object itself:

CustomVal

instead of:

CustomVal.SomeAttribute

The reason I want this is because, the COM object is too involved to initialize and by doing it this way, it will look like the original internal implementation that app offers.

+6  A: 

The usual way to wrap an object in Python is to override __getattr__ in your class:

class CustomVal(object):
    def __init__(self, value):
        self.value = value

    def __getattr__(self, attr):
        return getattr(self.value, attr)

So then you can do

>>> obj = CustomVal(wrapped_obj)
>>> obj.SomeAttributeOfWrappedObj

You can also override __setattr__ and __delattr__ to enable setting and deleting attributes, respectively (see the Python library documentation).

dF
+2  A: 

You just might be overthinking this... You can put anything you want into your val, then call whatever method of the object you want:

>>> val = ThingaMoBob(123, {p:3.14}, flag=False)
>>> val.SomeCrazyMathod()

Am I missing something?

scrible
I think he wants the new object to implement the exact same interface of the object he passes to its constructor. A sort of GoF-style decorator pattern...
Joe Holloway
If it implements the same interface, then -- well -- isn't it just the original object? Why wrap it? Just use it.
S.Lott
@S.Lott It is not necessarily the original object. From wikipedia: In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing class dynamically. check: http://en.wikipedia.org/wiki/Decorator_pattern
Martin