How can I declare a few methods with the same name, but with different numbers of parameters or different types in one class?
What must I change in the following class?>
class MyClass:
def __init__(this, foo_str, bar_int):
this.__foo = foo_str
this.__bar = bar_int
def foo(this, new=None):
if new != None:
try:
this.__foo = str(new)
except ValueError:
print("Illegal value. foo unchanged.")
return this.__foo
def bar(this, new=None):
if new != None:
try:
this.__bar = int(new)
except ValueError:
print("Illegal value. bar unchanged.")
return this.__bar
obj = MyClass("test", 42)
print(obj.foo(), obj.bar())
print(obj.foo("tset"), obj.bar(24))
print(obj.foo(42), obj.bar("test"))
Output:
test 42
tset 24
Illegal value. bar unchanged.
42 24