5

I need to return an instance of Bike in the constructor. For example:

class Bike(object):
    def __init__(self,color):
        self.bikeColor = color
        return self #It should return an instance of the class; is this not right?

myBike = Bike("blue")

When I do the above, I get the following error:

TypeError: __init__() should return None, not 'Bike'

If this is the case, how could I return an instance if its only suppose to return None?

glglgl
  • 89,107
  • 13
  • 149
  • 217
user965402
  • 75
  • 1
  • 4

1 Answers1

5
class Bike(object):
    def __init__(self, color):
        self.bikeColor = color

myBike = Bike("blue")

Is enough. In Python, __init__ is not really a constructor - it's an initializer. It takes an already constructed object and initializes it (for example, setting its bikeColor attribute.

Python also has something closer to a constructor semantically - the __new__ method. You can read about it online (here is a good SO discussion), but I suspect you don't really need it at this point.

Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 1
    `__init__` is just as much a constructor as any C++ or Java constructor, which also initialize the members of objects that already exist by the time they're called. I don't recall seeing `return this` in any C++ or Java constructors. The `__new__` method does something **you can't do** in Java or C++. I see it very often claimed that `__init__` should be called an initializer, while `__new__` is a constructor, and it really confuses me. – Ben Oct 24 '11 at 04:44
  • 1
    Sounds like you have a dispute with the terminology. The important thing to note is that Eli's description of what happens is essentially correct on all counts. If you want to call it something different, that's up to you. – Raymond Hettinger Oct 24 '11 at 05:19
  • @Raymond Yes, I have a dispute with the terminology. I don't want to call it something different, I want to keep using the same word for the concept that was in use for decades before Python was developed. "`__init__` is not really a constructor" is needlessly confusing for new Python programmers who are already familiar with constructors, especially when you follow it up with "`__new__` is a constructor", as `__new__` behaves even **less** like a Java/C++ constructor than `__init__` does. – Ben Oct 24 '11 at 05:30