Jack
Jack

Reputation: 95

None type in _init_ method

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.

Upvotes: 1

Views: 425

Answers (3)

Gio
Gio

Reputation: 3340

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.

Upvotes: 1

Yuri Malheiros
Yuri Malheiros

Reputation: 1410

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

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881477

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

Upvotes: 2

Related Questions