0

I have a class with the following structure:

class Example:
    def __init__(self, value, foo):
        self.value = value
        self.foo = foo
        self.bar = self.modify_stuff(value, foo)

    def modify_stuff(self, value, foo):
        """ some code """
        pass

I want to create an instance of the class, and then be able to refer to value directly, like this:

ex = Example(3, 'foo')
ans = 5 + ex

Instead of:

ans = 5 + ex.value

How can I do this?

3
  • 2
    Python doesn't do implicit conversions, period. It's literally in the zen. The best you can do is manually implement __add__/__radd__/etc to have the appropriate behavior Commented Jul 1, 2022 at 2:51
  • @Brian, but what about pandas.DataFrame? if I create something like df = pd.DataFrame([1, 2, 3, 4]) I can access the data directly from df (like df + 5), I don't need to do something like df.data + 5 Commented Jul 1, 2022 at 2:56
  • Yes, because pandas manually implemented __add__/__radd__/etc to have the appropriate behavior. Commented Jul 1, 2022 at 2:58

1 Answer 1

1

Rewrite the add and radd:

class Example:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        if isinstance(other, Example):
            return self.value + other.value

        return self.value + other

    def __radd__(self, other):
        if isinstance(other, Example):
            return self.value + other.value

        return self.value + other


print(Example(3) + 5)
print(Example(4) + Example(2))

# 8
# 6
Sign up to request clarification or add additional context in comments.

2 Comments

Cool things you learn everyday!
Learning from each other ^u^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.