类可以在Python中实例化自己吗? [关闭]

问题描述 投票:-1回答:1

[在StackExchange上,我发现有人问JavaPHP这个问题,而不是Python。所以我想知道一个类是否有可能在Python中实例化自己?如果是,它将是什么样?如果没有,为什么不呢?

提前感谢。

python class oop instantiation
1个回答
0
投票
>>> class MyClass:
...   def __init__(self, a):
...     self.a = a
...     if a < 10:
...       self.myObj = MyClass(a+1)
...
>>> myObj = MyClass(0)
>>> myObj.a
0
>>> myObj.myObj.a
1
>>> myObj.myObj.myObj.a
2

是的,它可以实例化自己。

© www.soinside.com 2019 - 2024. All rights reserved.