## AutoPython 5 Junior Poster

Okay, I wrote a simple calculator, not in GUI form, but a calculator for simple stuff. So I'm wondering, would this layout be considered OO? I think this is how it works. Now I do know that I didn't use an object to handle the class since it just wasn't necessary. Now I know that making a class wasn't totally necessary for this program, but I'm just curious if this would be the general layout. So here's the code:

``````import os
import math
import fractions

if os.name == "nt":
os.system("color 48")
os.system("title Calculator")
def clear():
os.system("cls")

else:

def clear():
os.system("clear")

class Calc:

clear()
print ("Welcome to calculator!")
print ("----------------------")
print ("1) Exponents          ")
print ("2) Division           ")
print ("3) Multiplication     ")
print ("5) Subtraction        ")
print ("6) Square Root        ")
print ("7) Simplify Fractions ")
print ("8) Factors            ")
print ("9) Exit               ")
print ("----------------------")

if ( menu in list("123456789") ) == False:
clear()
print ("Please type a valid option!")
input ()

def exp():
clear()
print ("? to the - power equals -")
p1 = int(input())
print ()
print (p1, "to the ? power equals -")
p2 = int(input ())
print ()
p3 = pow(p1, p2)
print (p1, "to the", p2, "power equals", p3)
input ()

def div():
clear()
print ("? divided by - equals -")
d1 = int(input())
print ()
print (d1, "divided by ? equals -")
d2 = int(input())
print ()
d3 = d1/d2
if (d1 % d2) == 0:
d3 = int(d3)
print (d1, "divided by", d2, "equals", d3)
input ()

def times():
clear()
print ("? multiplied by - equals -")
m1 = int(input())
print ()
print (m1, "multiplied by ? equals -")
m2 = int(input())
print ()
m3 = m1*m2
print (m1, "multiplied by", m2, "equals", m3)
input ()

clear()
print ("? plus - equals -")
a1 = int(input())
print ()
print (a1, "plus ? equals -")
a2 = int(input())
print ()
a3 = a1+a2
print (a1, "plus", a2, "equals" ,a3)
input ()

def minus():
clear()
print ("? minus - equals -")
s1 = int(input())
print ()
print (s1, "minus ? equals -")
s2 = int(input())
print ()
s3 = s1-s2
print (s1, "minus", s2, "equals", s3)
input ()

def square():
clear()
print ("The Square Root of ? is -")
sqrt1 = int(input())
sqrt2 = math.sqrt(sqrt1)
if ( str(sqrt2).split(".")[1] ) == "0":
sqrt2 = int(sqrt2)

print ()
print ("The Square Root of", sqrt1, "is", sqrt2)
input ()

def frac():
clear()
print ("?/- simplified is -/-")
fr1 = int(input())
fr11 = str(fr1)
print ()
print (fr11 + "/- simplified is -/-")
fr2 = int(input())
fr22 = str(fr2)
print ()
fr3 = fractions.Fraction(fr1, fr2)
fr33 = str(fr3)
print (fr11 + "/" + fr22, "simplified is", fr33)
input ()

def factors():
clear()
f = int(input("Type the number you would like to find the factors of: "))
f2 = []
for f1 in range(f + 1):
if f1 != 0:
if (f % f1) == 0:
f2.append(str(f1))
print ("The factors of", f, "are", ",".join(f2))
input ()

methods = [
Calc.exp,
Calc.div,
Calc.times,
Calc.minus,
Calc.square,
Calc.frac,
Calc.factors
]

What you have in your class right now are functions, not methods. You can turn your functions into methods with 'self'. This way you can also avoid globals outside the class, like your method list.

## lrh9 95

It's more object oriented than most code posted here, but there are more ways to use object oriented design and code in this program.

For instance, there could be a general class for a menu.

## scru 909

Not that I actually think that everything has to be OOP mind you (some small programs are just better off without it), but take for example your methods list. Why is your class directly manipulating an external object which it does not own (or was not given)?

What does displaying a menu have to do with a calculator? I don't necessarily agree that you need a class for something so small though. Perhaps a function that returns the index of the function selected, or better yet the name (so you can just do `getattr(c, name)()` )

## vegaseat 1,735

You have used a class to group functions together. This is the most simple form of class encapsulation. They are all functions that belong together, so it makes sense.

BTW, nice code that uses some features of Python3.

## AutoPython 5

(some small programs are just better off without it)

I already stated that in my original post.

Why is your class directly manipulating an external object which it does not own (or was not given)?

I had this weird problem. Because the list uses Methods from the Calc class, it wouldn't let me use the Calc class until it was totally defined. Which didn't make sense to me because a class does not use it's information while it's being defined.

What does displaying a menu have to do with a calculator?

Well, what would a program be without a menu? I put the Menu as part of the class because that went with the program.

## vegaseat 1,735

What you have in your class right now are functions, not methods. You can turn your functions into methods with 'self'. This way you can also avoid globals outside the class, like your method list.

commented: why oh why did I not see that? +4

## scru 909

What you have in your class right now are functions, not methods. You can turn your functions into methods with 'self'. This way you can also avoid globals outside the class, like your method list.

Whoa hey I did not even notice that! Yeah dude, to make methods in python Classes, set self as the first argument of every routine. To call a method from any method within the same class, do `self.methodname()` (note that you don't put self back in, when calling methods, python automatically sends in the object instance, ergo self, as the first argument.)

## AutoPython 5

Oh, I didn't know that they're only called methods when the class is assigned an object.

## snippsat 661

This code had been better without a class,and this is not the OOP way of thinking.
One function for Addition/Division....... can be shorten by eval()

``````>>> a = eval('5+8886/45*4554545')
>>> a
899370824.3333334``````

Here an example with class.

``````import math
class Calculator(object):
def calculate(self, expression):
self.value = eval(expression)

def square(self, sqrt1):
'''This look like a function,but inside a class is called a method'''
self.b = math.sqrt(sqrt1)

def __str__(self):
return self.value
return self.b

#here a make the method of class short
#and i do user_input and printing outside of the class(you can of course make a menu but not in the class)
a = Calculator()
print('Calculate +-*/ and Square Root')
b = input('values')
a.calculate(b)
print('The sum of %s is %d' % (b, a.value))

c = int(input('Enter Square Root value'))
a.square(c)
print('The square Root of %d is %d' % (c, a.b))

''' my output-->
Calculate +-*/ and Square Root
The sum of 45+78*4545/56 is 6375
The square Root of 25 is 5
'''``````

## AutoPython 5

This code had been better without a class

This is really starting to annoy me, in the first post I already stated that the program didn't need a class, but I added it anyway just see.

## snippsat 661

This is really starting to annoy me

I did this just to show an alternative way of thinking,because you ask about OO.

It is not to put your code down.
One the best way to learn is to get input from other.

So you shoul not be annoyed but rather look at it as a good way to learn.

If someone told me that writing a function for +-*/ rather than use eval() is a good thing for safe code.
I would not argue about that.
Because eval() can be used in a bad way.

``````>>> eval("__import__('os').remove('file')")
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
eval("__import__('os').remove('file')")
File "<string>", line 1, in <module>
WindowsError: [Error 2] Systemet finner ikke angitt fil: 'file'``````

So it get an error that it dont find the file.
If correct path it had removed that file from my system.

``print eval("__import__('os').remove('file')", {"__builtins__": {}})``

## lrh9 95

I'd like to give a dissenting opinion.

All though functional design and code can be smaller than object oriented design and code for small programs, I still think it is better to always use object oriented programming techniques.

Why do I think this?

1) Object oriented design and code aids program clarity, helping software developers understand the purpose and function of a program. Writing a small program using object oriented programming - though it takes more time and forethought on the developer's part - can reduce the time it takes other developers to learn the program. It may even help the original developer after he or she is no longer familiar with the code.

2) Object oriented code is relocatable, reusable, and flexible. Using object oriented programming in Python, you can quickly place your most often used classes in modules and import them in all future programs you write. Object oriented programming provides the benefit of encapsulating and abstracting functionality, allowing developers to focus on interfacing code instead of rewriting the internal mechanics.

## AutoPython 5

Hm, I never thought of it that way.

(original post)
Now I know that making a class wasn't totally necessary for this program

some small programs are just better off without it

This code had been better without a class

.
This is really starting to annoy me

This is what I was talking about