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 751451
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T14:40:06+00:00 2026-05-14T14:40:06+00:00

I have a class that dynamically overloads basic arithmetic operators like so… import operator

  • 0

I have a class that dynamically overloads basic arithmetic operators like so…

import operator

class IshyNum:
    def __init__(self, n):
        self.num=n
        self.buildArith()

    def arithmetic(self, other, o):
        return o(self.num, other)

    def buildArith(self):
        map(lambda o: setattr(self, "__%s__"%o,lambda f: self.arithmetic(f, getattr(operator, o))), ["add", "sub", "mul", "div"])

if __name__=="__main__":
    number=IshyNum(5)
    print number+5
    print number/2
    print number*3
    print number-3

But if I change the class to inherit from the dictionary (class IshyNum(dict):) it doesn’t work. I need to explicitly def __add__(self, other) or whatever in order for this to work. Why?

  • 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-14T14:40:06+00:00Added an answer on May 14, 2026 at 2:40 pm

    The answer is found in the two types of class that Python has.

    The first code-snippet you provided uses a legacy “old-style” class (you can tell because it doesn’t subclass anything – there’s nothing before the colon). Its semantics are peculiar. In particular, you can add a special method to an instance:

    class Foo:
       def __init__(self, num):
          self.num = num
          def _fn(other):
             return self.num + other.num
          self.__add__ = _fn
    

    and get a valid response:

    >>> f = Foo(2)
    >>> g = Foo(1)
    >>> f + g
    3
    

    But, subclassing dict means you are generating a new-style class. And the semantics of operator overloading are different:

    class Foo (object):
       def __init__(self, num):
          self.num = num
          def _fn(other):
             return self.num + other.num
          self.__add__ = _fn
    >>> f = Foo(2)
    >>> g = Foo(1)
    >>> f + g
    Traceback ...
    TypeError: unsupported operand type(s) for +: 'Foo' and 'Foo'
    

    To make this work with new-style classes (which includes subclasses of dict or just about any other type you will find), you have to make sure the special method is defined on the class. You can do this through a metaclass:

    class _MetaFoo(type):
        def __init__(cls, name, bases, args):
            def _fn(self, other):
                return self.num + other.num
            cls.__add__ = _fn
    
    class Foo(object):
        __metaclass__ = _MetaFoo
        def __init__(self, num):
            self.num = num
    
    >>> f = Foo(2)
    >>> g = Foo(1)
    >>> f+g
    3
    

    Also, the semantic difference means that in the very first case I could define my local add method with one argument (the self it uses is captured from the surrounding scope in which it is defined), but with new-style classes, Python expects to pass in both values explicitly, so the inner function has two arguments.

    As a previous commenter mentioned, best to avoid old-style classes if possible and stick with new-style classes (old-style classes are removed in Python 3+). Its unfortunate that the old-style classes happened to work for you in this case, where new-style classes will require more code.


    Edit:

    You can also do this more in the way you originally tried by setting the method on the class rather than the instance:

    class Foo(object):
        def __init__(self, num):
            self.num = num
    setattr(Foo, '__add__', (lambda self, other: self.num + other.num))
    >>> f = Foo(2)
    >>> g = Foo(1)
    >>> f+g
    3
    

    I’m afraid I sometimes think in Metaclasses, where simpler solutions would be better 🙂

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

Sidebar

Ask A Question

Stats

  • Questions 466k
  • Answers 466k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer if you're planning to upgrade to a newer version of… May 16, 2026 at 1:37 am
  • Editorial Team
    Editorial Team added an answer Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource.… May 16, 2026 at 1:37 am
  • Editorial Team
    Editorial Team added an answer You need to clear #scat list first and then populate… May 16, 2026 at 1:37 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.