-2

I am trying to combine some class methods or apply init value on itself without success.

class numOper:
    def __init__(self, x):
        self.x = x
        
    def multiply(self, x):
        self.x *= x

    def add(self, x):
        self.x += x


a = numOper(5)
print(a.x) # 5
a.multiply(3)
print(a.x) # 15
a.add(7)
print(a.x) # 22


a = numOper(5) # x = 5
a.multiply(3).add(7) # Error; trying multiply and then add to result
print(a.x)

a = numOper(5) # x = 5
a.multiply(a) # Error; trying to multiply by itself

These result in

AttributeError: 'NoneType' object has no attribute 'multiply'
AttributeError: 'NoneType' object has no attribute 'add'

Is there any way to do these? Or investigate?

In procedural python, this seems to works.

a = 5

def addf(a):
    a += a
    return a

addf(a)

or

a = 5

def addf(a):
    a += a
    return a

def double(a):
    a *= 2
    return a

double(addf(a))
  • You have to return `self` to be able to chain method calls – DeepSpace Oct 12 '21 at 14:58
  • What DeepSpace said... However, be sure to carefully consider how this API can be confusing since it modifies the state of the `numOper` internally as a side effect. – AKX Oct 12 '21 at 14:59
  • Silly, could have thought of that! Thanks all contributors. – learning_python_self Oct 12 '21 at 15:01
  • You may also want to look at special methods for your class, like `__iadd__`, which specifically overrides `+=` so you could have `a += 3` in your code. – NGilbert Oct 12 '21 at 15:02

1 Answers1

0

multiply and add don't return anything explicitly, so implicitly they return None, hence the error you're seeing. You could instead explicitly return self so you can continue calling methods on it:

class numOper:
    def __init__(self, x):
        self.x = x
        
    def multiply(self, x):
        self.x *= x
        return self # Here!

    def add(self, x):
        self.x += x
        return self # And here!
Mureinik
  • 297,002
  • 52
  • 306
  • 350