我需要在构造函数中返回 Bike 的实例。例如:
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")
Run Code Online (Sandbox Code Playgroud)
当我执行上述操作时,出现以下错误:
TypeError: __init__() should return None, not 'Bike'
Run Code Online (Sandbox Code Playgroud)
如果是这种情况,如果只是假设的话,我该如何返回一个实例return None?
class Bike(object):
def __init__(self, color):
self.bikeColor = color
myBike = Bike("blue")
Run Code Online (Sandbox Code Playgroud)
足够。在Python中,__init__它并不是真正的构造函数——它是一个初始化器。它需要一个已经构造的对象并初始化它(例如,设置它的bikeColor属性。
Python 还有一些在语义上更接近构造函数的东西——__new__方法。你可以在线阅读它(这是一个很好的SO讨论),但我怀疑你现在并不真正需要它。
| 归档时间: |
|
| 查看次数: |
4914 次 |
| 最近记录: |