【发布时间】:2012-05-30 06:19:25
【问题描述】:
下面的python代码有效吗?
class Test:
def __init__(self):
self.number = 5
def returnTest(self):
return Test()
【问题讨论】:
下面的python代码有效吗?
class Test:
def __init__(self):
self.number = 5
def returnTest(self):
return Test()
【问题讨论】:
是的,它是有效的。该类是在您创建对象并调用returnTest 方法时定义的。
In [2]: x = Test()
In [3]: y = x.returnTest()
In [4]: y
Out[4]: <__main__.Test instance at 0x1e36ef0>
In [5]:
但是,如果方法像工厂一样工作,您可能需要考虑使用 classmethod 装饰器。当继承和其他烦恼出现时,这会有所帮助。
【讨论】:
是的,它是有效的。 returnTest 在被调用之前不会运行。它不会创建无限循环,因为不会在新创建的对象上调用该方法。
【讨论】:
是的,它可以工作,但 returnTest() 似乎总是同一个 Test 实例。
class Test:
def __init__(self):
self.number = 5
def returnTest(self):
return Test()
t = Test()
print t
print t.returnTest()
print t.returnTest()
$ python te.py
<__main__.Test instance at 0xb72bd28c>
<__main__.Test instance at 0xb72bd40c>
<__main__.Test instance at 0xb72bd40c>
这适用于 Python 2.7 和 3.2。 @classmethod 没有任何区别。有趣的是,pypy 每次都返回一个不同的实例:
$ pypy te.py
<__main__.Test instance at 0xb6dcc1dc>
<__main__.Test instance at 0xb6dcc1f0>
<__main__.Test instance at 0xb6dcc204>
【讨论】:
是的。这是一个有效的python代码。许多编程语言允许返回正在定义的类的实例。想想 singleton 模式。
【讨论】: