Returning an instance of a class from the constructor

I need to return a Bike instance to the constructor. For instance:

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 this, I get the following error:

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

If so, how can I return an instance if it is suppose only return None ?

+4
source share
2 answers
 class Bike(object): def __init__(self, color): self.bikeColor = color myBike = Bike("blue") 

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

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

+4
source

Well, maybe you came up with something like this. where you want to return the constructor. In this case, you can use a separate method for this. for example,

 class A: def __init__(self): self.data = [] def newObj(self): return A() 
0
source

All Articles