PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 7, 2022

[FIXED] How to return a default attribute for a class' instance?

 July 07, 2022     class, oop, python     No comments   

Issue

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?


Solution

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


Answered By - maya
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,204,562

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing