This program modifies objects of the class “myclass” _x and _y, but I don’t pass it as a parameter to the function try_block. How do the objects get modified?
class AddSub:
def _init_(self): #how do default parameters work?
self._x, _y
def set_x(self, num):
self._x = num
def set_y(self, num):
self._y = num
def add(self):
return self._x + self._y
def sub(self):
return self._x - self._y
def try_block():
try:
ch = int(input("type 1 to add, and 2 to subtract: "))
myclass.set_x(int(input("enter an x value: "))) #how does myclass get modifed?
myclass.set_y(int(input("enter a y value: ")))
return ch
except ValueError:
print("Invalid entry.")
ch = try_block()
return ch
myclass = AddSub()
choice = try_block()
if choice == 1:
print(myclass.add())
elif choice == 2:
print(myclass.sub())
Before I go into answering your question, I want to mention some things about terminology. Your
myclassvalue is an instance, not a class. You do have a class in your code, namedAddSub. When you calledAddSub()you created an instance of that class. It’s important to learn the right terminology for things like this, so you can ask good questions and understand the answers you get back.Your code comes close to working because you’re saving an instance of the
AddSubclass to a global variable namedmyclass. Later, you call some methods on that global variable from thetry_blockfunction. This is legal in Python, though generally not recommended.Instead, you should pass the object as an argument:
You’d call it by passing an instance of your AddSub class to the function:
This is much nicer because it doesn’t depend on a global variable having a specific value to work and you can call it with many different
AddSubinstances, if you want.One part of your code that’s currently broken is the
AddSubclass’s constructor. There’s no need to declare variables. You can just assign to them whenever you want. If you want to have default values set, you can do that too:If instead you want to be able to set the values when you construct the object, you can add additional parameters to the
__init__method. They can have default values too, allowing the caller to omit some or all of them:With that definition, all of these will be valid ways to construct an
AddSubinstance:Finally a point that is mostly independent of your main question: Your
try_blockfunction is both poorly named, and implemented in a more complicated way than necessary. Instead of being recursive, I think it would make more sense as a loop, like in this psuedocode version: