Ty Staszak - 1 year ago 75

Python Question

I'm writing some classes:

`bean_version = "1.0"`

from random import randint

console = []

print "Running Bean v%s" % bean_version

#Math Function

class math(object):

def __init__(self, op1 = 0, op2 = 0):

self.op1 = op1

self.op2 = op2

def add(self):

return self.op1 + self.op2

def sub(self):

return self.op1 - self.op2

def mul(self):

return self.op1 * self.op2

def div(self):

return self.op1 / self.op2

What I realized I could do is:

`math.add(math(3,5))`

==>8

What I'm wondering is, is there any way to be able to do:

`math.add(3,5)`

Python 2.7.10

Answer Source

That is possible. In this case you use the class just as a way to logically group your operators (add, sub, mul, div) and you don't really need to initialize the operands in the class instance itself. This calls for the `staticmethods`

decorator, and the code looks like the one below.
You can also see it in action here: https://eval.in/639864

```
bean_version = "1.0"
from random import randint
console = []
print "Running Bean v%s" % bean_version
#Math Function
class math(object):
def __init__(self):
pass
@staticmethod
def add(op1, op2):
return op1 + op2
@staticmethod
def sub(op1, op2):
return op1 - op2
@staticmethod
def mul(op1, op2):
return op1 * op2
@staticmethod
def div(op1, op2):
return op1 / op2
print math.add(3,5)
print math.sub(3,5)
print math.mul(3,5)
print math.div(3,5)
```