1

I am beginner in python. I cant understand simple thing with type None . When I assign None values to my parameters in constructor . I get error. What is the trick . Code with error:

class A(object):
  def __init__(self):
    self.root = None

  def method_a(self, foo):
    if self.root is None:
       print self.root + ' ' + foo


a = A()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

The error:

Traceback (most recent call last):
  File "C:/Users/Dmitry/PycharmProjects/Algorithms/final_bst.py", line 11, in <module>
    a.method_a('Sailor!') # We only pass a single argument
  File "C:/Users/Dmitry/PycharmProjects/Algorithms/final_bst.py", line 7, in method_a
    print self.root + ' ' + foo
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

As soon as I change None type in init for something like string variable it works correctly.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
Jack
  • 97
  • 3
  • 10
  • 1
    What do you expect `None + ' '` to do? The problem has nothing to do with `__init__` as such; the problem is that you can't add None to a string, as the error message says. – BrenBarn Mar 09 '15 at 00:07

3 Answers3

2

The error is not in __init__ but later, in the expression you're trying to print:

print self.root + ' ' + foo

You can use + to concatenate strings, but None is not a string.

So, use string formatting:

print '{} {}'.format(self.root, foo)

or, far less elegantly, make a string explicitly:

print str(self.root) + ' ' + foo
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
1

The problem is that you are trying to concatenate None with two strings ' ' and 'Sailor!', and None is not a String.

Yuri Malheiros
  • 1,400
  • 10
  • 16
1

You are concatenating None with strings. However None is not a string, it's an object, if you want to print an object you must use str(<Obj>), this will call the __str__ method of the object, or if no __str__ method is given, the result of __repr__ will be printed.

The difference between __str__ and __repr__ is explained here.

Community
  • 1
  • 1
Gio
  • 3,242
  • 1
  • 25
  • 53