tags:

views:

71

answers:

3

Hi everyone!

I want to do the following: I have a container-class Container, it has attribute attr, which refers to another class OtherClass.

class OtherClass:
    def __init__(self, value): 
        self._value = value 

    def default(self): 
        retirn self._value 

    def another(self): 
        return self._value ** 2 

    def as_str(self): 
        return 'String: %s' % self._value

class Container: 
    def __init__(self, attr): 
        self.attr = OtherClass(attr)

I want to:

x = Container(2) 

x.attr # when accessing the attribute - return value from default method
2 
x.attr.another() # but also an attribute can be treated as an object 
4 
x.attr.as_str()
'String: 2'

How can I do this?

A: 

You can't, unless OtherClass overrides __int__() and you then put it through int() to get the integer value.

Ignacio Vazquez-Abrams
A: 

What is attr meant to be? You can't have it both ways; either it's the return value of some function or it's an instance of OtherClass.

How about making OtherClass inherit from Integer?

katrielalex
Returned values can be different types.
Homer
In which case why can't you call `x.attr.default()` when you want its value?
katrielalex
I want to give developers a simple API. If no method specific - return the default value.In any case, thanks for help.
Homer
+1  A: 

Not sure if this is what you need. Seems like an odd design to me

>>> class OtherClass(int):
...     def __init__(self, value): 
...         self._value = value 
...     def another(self): 
...         return self._value ** 2 
... 
>>> class Container: 
...     def __init__(self, attr): 
...         self.attr = OtherClass(attr)
... 
>>> x=Container(2)
>>> x.attr
2
>>> x.attr.another()
4

just-because-you-use-classes-doesn't-mean-it's-OO-ly gnibbler

gnibbler