Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7548609
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T09:44:30+00:00 2026-05-30T09:44:30+00:00

I want to define operators for a class instance within a class function, like

  • 0

I want to define operators for a class instance within a class function, like so:

class MyClass(object):

    @property
    def _arithmetic_threshold(self):
        return self.threshold # this will be defined somewhere

    @_arithmetic_threshold.setter
    def _arithmetic_threshold(self,value):
        self.threshold = value
        self._define_arithmetic_attributes()

    def _define_arithmetic_attributes(self):
        """
        Wrapper to define all arithmetic attributes (in order to allow threshold changes)
        """

        self.__add__ = self._operation_wrapper(np.add,threshold=self._arithmetic_threshold)
        self.__sub__ = self._operation_wrapper(np.subtract,threshold=self._arithmetic_threshold)
        self.__mul__ = self._operation_wrapper(np.multiply,threshold=self._arithmetic_threshold)
        self.__div__ = self._operation_wrapper(np.divide,threshold=self._arithmetic_threshold)

However, this doesn’t seem to work – I feel like I’m missing something about how the operators -,+, etc, call these functions. i.e.:

class MyClass2(object):
    def __add__(self,other,threshold=None):
        if threshold is not None:
            return self+other
        else:
            # do something here involving checking a threshold....
            pass

in MyClass2, the behavior of __add__ will be different. Can anyone explain how they are different, and how to make the behavior of the operator methods in MyClass similar to MyClass2?

EDIT: Just to make clear why I’m trying to do this, here’s _operation_wrapper. The class this is a method of is a “Spectrum” object, which has an X-axis and a Y-axis. The goal is to allow arithmetic on the Y axes, but only if the X axes match. However, it is acceptable for them to match to, say, 1/5th of a pixel size, so I wanted to do more that pure ‘exact’ matching.

def _operation_wrapper(operation):
    """
    Perform an operation (addition, subtraction, mutiplication, division, etc.)
    after checking for shape matching
    """

    def ofunc(self, other): 
        if np.isscalar(other):
            newspec = self.copy()
            newspec.data = operation(newspec.data, other) 
            return newspec
        else: # purely for readability

            if self._arithmetic_threshold == 'exact':
                xarrcheck = all(self.xarr == other.xarr)
            else:
                if self._arithmetic_threshold_units is None:
                    # not sure this should ever be allowed
                    xarrcheck = all((self.xarr-other.xarr) < self._arithmetic_threshold)
                else:
                    xarrcheck = all((self.xarr.as_unit(self._arithmetic_threshold_units)-other.xarr.as_unit(self._arithmetic_threshold_units)) < self._arithmetic_threshold)

            if self.shape == other.shape and xarrcheck:
                newspec = self.copy()
                newspec.data = operation(newspec.data, other.data)
                return newspec
            elif self.shape != other.shape:
                raise ValueError("Shape mismatch in data")
            elif not xarrcheck:
                raise ValueError("X-axes do not match.")

    return ofunc
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T09:44:32+00:00Added an answer on May 30, 2026 at 9:44 am

    Special methods like __add__() are looked up on the type of the object, not on the instance. So

    a + b
    

    is roughly translated to

    type(a).__add__(a, b)
    

    This means that setting __add__ on the instance does not do anything useful (except for making a.__add__(b) work).

    Your example is a bit incomplete, so I can’t provide full working code. You might be able to move the code from _define_arithmetic_attributes() to the class body and access self.threshold from inside operation_wrapper().

    (Note that I don’t get the point of the _arithmetic_threshold property. Why don’t you simply access self.threshold itself?)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to define a JavaScript class, Foo. Foo = function(value){ this.value = value;
I want to define something like this in php : $EL = \n<br />\n;
I want to define a following function: if(stmtToFinalize) { NSLog(@Finalizing statement stmtToFinalize); if (sqlite3_finalize(stmtToFinalize)
I want to define some properties on a class using the [Indexable()] attribute in
I want to define a class that supports __getitem__ , but does not allow
I want to define a constant in objective-c. Previously I had the following function:
I want to define a class method that has access to a local variable.
I want to put a text description of a class instance onto an ostream,
What I mean is to define an instance of a type class that applies
So I have a FileReader class, it looks like this: #define DISALLOW_COPY(type) \ type(const

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.