22

以下python代码有效吗?

class Test:
  def __init__(self):
    self.number = 5

  def returnTest(self):
    return Test()
4

4 回答 4

27

是的,它是有效的。类是在您创建对象并调用returnTest方法时定义的。

In [2]: x = Test()

In [3]: y = x.returnTest()

In [4]: y
Out[4]: <__main__.Test instance at 0x1e36ef0>

In [5]: 

但是,在方法像工厂一样的情况下,您可能需要考虑使用classmethod装饰器。当继承和其他烦恼出现时,这会有所帮助。

于 2012-05-30T06:23:00.510 回答
2

是的,它是有效的。 returnTest在被调用之前不会运行。它不会创建无限循环,因为不会在新创建的对象上调用该方法。

于 2012-05-30T06:24:05.920 回答
1

是的,它有效,但似乎 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>
于 2012-05-30T06:28:13.350 回答
0

是的。这是一个有效的python代码。许多编程语言允许返回正在定义的类的实例。想想单例模式。

于 2012-05-30T06:24:50.940 回答