1

I am transitioning from Java to Python and am currently stumped with this seemingly simple code whose Java equivalent works just fine.

I am trying to create an object called TestClass that either takes one argument called text or no arguments; in which case a default string "foo" is assigned to the text instance variable.

class TestClass(object):

   def __init__(self):
      self.text = "foo"

   def __init__(self, text):
      self.text = text


a = TestClass()
b = TestClass("bar")

I really am unable to pinpoint the issue and get the following error:

a = TestClass()

TypeError: init() missing 1 required positional argument: 'text

Your help would be appreciated, Thank you!

Community
  • 1
  • 1
Oamar Kanji
  • 1,824
  • 6
  • 24
  • 39

1 Answers1

2

Java doesn't have default values for parameters (last time I checked at least)

In Python, you cannot override methods with different parameters (well it's possible, but the first definition becomes invisible so that's not very useful).

So what you're trying to do translates like this:

def __init__(self, text="foo"):
   self.text = text

That's okay with strings, integers, floats, but be careful with mutable types though: "Least Astonishment" and the Mutable Default Argument

Also, if you want to "emulate" same method name with different argument types, you have to define one method (that doesn't change) and use dynamic type checking to decide what to do:

def __init__(self, param):
   if isinstance(param,str):
       # param is a string
   elif isinstance(param,int):
       # param is an integer
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219