python类可以返回其类的新实例吗?

时间:2012-05-30 06:19:25

标签: python class

以下python代码是否有效?

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

  def returnTest(self):
    return Test()

4 个答案:

答案 0 :(得分:17)

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

In [2]: x = Test()

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

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

In [5]: 

但是,如果方法的行为类似于工厂,您可能需要考虑使用classmethod装饰器。当继承和其他烦恼出现时,这可能会有所帮助。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

是的,它有效,但看起来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>